How to access a method from an external jar at runtime (part2)?
This is a continuation of the post How to access a method from an external banner at runtime?
McDowell responded with code:
public class ReflectionDemo {
public void print(String str, int value) {
System.out.println(str);
System.out.println(value);
}
public static int getNumber() { return 42; }
public static void main(String[] args) throws Exception {
Class<?> clazz = ReflectionDemo.class;
// static call
Method getNumber = clazz.getMethod("getNumber");
int i = (Integer) getNumber.invoke(null /* static */);
// instance call
Constructor<?> ctor = clazz.getConstructor();
Object instance = ctor.newInstance();
Method print = clazz.getMethod("print", String.class, Integer.TYPE);
print.invoke(instance, "Hello, World!", i);
}
}
I added the following method:
public void print2(String[] strs){
for(final String string : strs ){
System.out.println(string);
}
}
and modified main to include these two lines:
Method print2 = clazz.getDeclaredMethod("print2", new Class[]{String[].class});
print2.invoke(instance, new String[]{"test1", "test2"});
However, instead of viewing
test1
test2
I am getting the following exception:
Exception on thread "main" java.lang.IllegalArgumentException: wrong number of arguments
I went through the Sun Java tutorials, I gave the arguments to their own object before the call, and I reloaded the arrays and they all fail. Can anyone explain what I am doing wrong here?
Thanks, Todd
+2
source to share