IllegalArgumentException: invalid number of arguments

I am 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: the wrong number of arguments, even if the two methods take no arguments.

I tried passing null to the invoke method, but that causes NPE.

+4
source share
2 answers

You are actually calling the methods correctly, the problem is that the Class.getMethods () method returns ALL methods in the class, INCLUDING those that are inherited from superclasses such as Object in this case. The documentation states:

Returns an array containing method objects that reflect all the public methods of a class or interface represented by this class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

In this case, you can end up calling Object.equals without any arguments. The same applies to Object.wait methods, etc.

+7
source

According to the documentation :

If the number of formal parameters required by the base method is 0, the provided argument array can be 0 or zero in length.

Have you tried this?

 m.invoke(cls, null); 
0
source

Source: https://habr.com/ru/post/1385528/


All Articles