I’m trying to run the following code:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflection {
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException,
InvocationTargetException, IllegalArgumentException {
Class<Cls> cls = Cls.class;
Method[] methods = cls.getMethods();
for (Method m : methods) {
m.invoke(cls);
}
}
}
class Cls {
public static void method1() {
System.out.println("Method1");
}
public static void method2() {
System.out.println("Method2");
}
}
I keep getting an IllegalArgumentException: wrong number of arguments, even though the two methods take no arguments.
I tried passing null to the invoke method, but that throws a NPE.
You are actually invoking the methods correctly, the problem is that the Class.getMethods() method returns ALL methods in the class, INCLUDING those inherited from super classes, such as Object in this case. The documentation states:
In this case you might end up calling Object.equals without any arguments, for example. The same goes for the Object.wait methods etc.