Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with varargs and reflection

Tags:

Simple question, how make this code working ?

public class T {      public static void main(String[] args) throws Exception {         new T().m();     }      public // as mentioned by Bozho     void foo(String... s) {         System.err.println(s[0]);     }      void m() throws Exception {         String[] a = new String[]{"hello", "kitty"};         System.err.println(a.getClass());         Method m = getClass().getMethod("foo", a.getClass());         m.invoke(this, (Object[]) a);     } } 

Output:

class [Ljava.lang.String; Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)         at java.lang.reflect.Method.invoke(Method.java:597) 
like image 392
PeterMmm Avatar asked Apr 08 '10 14:04

PeterMmm


People also ask

How do you handle varargs in Java?

Important Points regarding Varargs Before JDK 5, variable length arguments could be handled in two ways: One was using overloading, other was using array argument. There can be only one variable argument in a method. Variable argument (Varargs) must be the last argument.

Is it good to use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

Can you pass an array for Varargs?

If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.


1 Answers

Test.class.getDeclaredMethod("foo", String[].class); 

works. The problem is that getMethod(..) only searches the public methods. From the javadoc:

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Update: After successfully getting the method, you can invoke it using:

m.invoke(this, new Object[] {new String[] {"a", "s", "d"}}); 

that is - create a new Object array with one element - the String array. With your variable names it would look like:

m.invoke(this, new Object[] {a}); 
like image 124
Bozho Avatar answered Oct 07 '22 16:10

Bozho