java - 非法参数异常 : wrong number of arguments

标签 java reflection

我正在尝试运行以下代码:

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");
    }
}

我不断收到 IllegalArgumentException:错误数量的参数,即使这两种方法都不带参数。

我尝试将 null 传递给 invoke 方法,但这会引发 NPE。

最佳答案

您实际上是在正确地调用方法,问题是 Class.getMethods() 方法返回类中的所有方法,包括从父类(super class)继承的方法,例如本例中的 Object。 documentation状态:

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

例如,在这种情况下,您最终可能会在没有任何参数的情况下调用 Object.equals。 Object.wait 方法等也是如此。

关于java - 非法参数异常 : wrong number of arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445771/

相关文章:

java - 使用基于计数的窗口连接两个流

Java Mongodb numberlong 查询

java - 来自 Arraylist 的自定义 ListView

c# - 如何将属性的 .NET 反射与每个对象相关联?

reflection - 如何找到对应的setter和getter?

c# - 我们的 C# 类成员有多少(多少) 'private'?

c# - 使用反射确定事件是否是静态的

java - 将数据结构化数据保存为 java 可执行文件的一部分

java - 为什么JFrame上有背景图片的按钮无法正常显示

c# - 如何创建具有反射类型的委托(delegate)闭包