views:

49

answers:

1

This is a continuation of the post http://stackoverflow.com/questions/1319661/how-does-one-access-a-method-from-an-external-jar-at-runtime

McDowell responded with the 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 seeing

test1
test2

I get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments

I have gone through the Sun Java tutorials, I have given the arguments their own object prior to the invocation, and I have reloaded the arrays, all with no success. Can anyone explain what I am doing wrong here?

Thanks, Todd

+3  A: 

Such are the problems with varargs!

print2.invoke(instance, new Object[] { new String[] {"test1", "test2"}});
Tom Hawtin - tackline
Yeah, notice that invoke takes in (Object, Object...) which means that the second parameter should technically be an Object[], so all the arguments you're passing have to be passed as shown above. Yuck. :-D
Brent Nash
@tackline, @brent, thanks. I am much lighter in the hair department over this. Glue, I need glue!!
Todd