I must miss something very fundamental. When I try to pass an array of any kind during a method invocation I get an error. However when I do it normally it works.
This is the complete code that fails
import java.lang.reflect.Method;
public class Main {
    public static void main(String[] args) throws Exception {
        // Normal
        MyClass.sayHello(new String[] {"StackOverflow"});
        // Reflection
        Method m = MyClass.class.getMethod("sayHello", String[].class);
        m.invoke(null, new String[]{"StackOverflow"});
    }
    static class MyClass {
        public static void sayHello(String[] args) {
            System.out.println("Hello " + args[0]);
        }
    }
}
The Exception thrown
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Main.main(Main.java:11)
String... does not work either btw.
 
Aucun commentaire:
Enregistrer un commentaire