понеділок, 28 лютого 2011 р.

Invocation of var-arg method via Reflection API

When trying to invoke the method accepting array or variable arguments, you should take few things into account.

The argument type to be matched is an array of variable argument type. So if you declare String... or String[] in your method's signature, you should match for String[].class in both cases.

// Test.java
package milkyway.Test;

public class Test {
    public static void main(String... args) {
        System.out.println("yo");
    }
}
 
// A long time later in a galaxy far far away
ClassLoader scl = ClassLoader.getSystemClassLoader();
Class c = scl.loadClass("milkyway.Test");
Method m = c.getMethod("main", String[].class);

Later, you may want to invoke the method, and you can be tempted to pass null, or an array to your method, but watch out. Neither of these will work

m.invoke(null);
m.invoke(null, null);
m.invoke(null, new String[0]);
m.invoke(null, new String[] { "one", "two", "three" });

All will result in java.lang.IllegalArgumentException with various reasons.

To make the invoke() happy, you should explicitly cast the argument to Object type:

m.invoke(null, (Object)null);
m.invoke(null, (Object)new String[0]);

If you want to pass no variable arguments in the case of var-arg method, pass null or empty array as we just did. This tells invoke() to call the method with empty list of variable arguments.

Немає коментарів:

Дописати коментар