groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: Reflection problem with varargs
Date Tue, 14 Jul 2020 19:14:18 GMT
On 14.07.20 19:55, Blake McBride wrote:
[...]
>      static Object myMethod(Object ... args) {
[...]
>      Method methp = groovyClass.getMethod("myMethod", ca);
>      Object r = methp.invoke(null,4,5);  // Here is where the error occurs
>      int x =1;// place for a breakpoint
[...]
> At the indicated location, I am getting the error:
>
> java.lang.IllegalArgumentException: wrong number of arguments
>
> I have tried a veriety of alternatives with no success. Any help would
> sure be appreciated.

If you call a varargs method in Java, the compiler is normally boxing
the arguments for you into an array. This means myMethod(4,5) becomes
myMethod(new Object[]{4,5}) as per the Java compiler. Groovy does the
something similar either by compiler (static mode) or at runtime
(dynamic mode).

But you are executing the method by reflection, which means you have no
support of the Groovy runtime or any compiler. In fact reflection does
not know varargs. That means methp.invoke(null,4,5) assumes you want to
invoke myMethod(int,int). Now the difficulty comes from that method
having varargs itself, but for the invoke itself, not for what it is
invoking. That means methp.invoke(null,4,5) becomes as per compiler
methp.invoke(null,new Object[]{4,5}). What you really need is an
Object[] in the Object[]:

   methp.invoke(null, new Object[]{new Object[]{4,5}})

If myMethod would take for example String... instead of Object... it
would be


   methp.invoke(null, new Object[]{new String[]{"4","5"}})

and maybe it becomes even more clear if we wanted to invoke
myMethod(int, String...):

   methp.invoke(null, new Object[]{
     1, new String[]{"a","b"}
   })

bye Jochen

Mime
View raw message