简体   繁体   English

调用反射Class.getMethod时发生异常

[英]Exception when invoke reflection Class.getMethod

I have below code which invokes a method using reflection. 我下面有代码调用使用反射的方法。 But I am getting, 但我明白了

java.lang.IllegalArgumentException: wrong number of arguments java.lang.IllegalArgumentException:参数数量错误

exception at Method.invoke. Method.invoke发生异常。 What is the reason? 是什么原因?

public class B {
    public static void main(String[] args) {
        A a = new A();
        Method m;
        try {
            m = a.getClass().getMethod("m3",Integer.class);
            m.invoke(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class A {    
    public void m3(Integer x){
        System.out.println("ssss");
    }
}

The invoke(Object, Object...) -method takes as it's first parameter the object that the method should be invoked on (as you did correctly) and then as a variable-length parameter any parameters that should be passed to the method call. invoke(Object, Object...) -方法需要,因为它是第一个参数,该方法应该被调用(如你做正确的)对象, 然后作为一个可变长度的参数应该传递方法调用的所有参数。

In your case, you're forgetting about the methods Integer -parameter. 在您的情况下,您忘记了Integer -parameter方法。 The method you're trying to call is A.m3() , which doesn't exist in the class. 您尝试调用的方法是A.m3() ,该方法在类中不存在。

The correct call would be: 正确的调用是:

m.invoke(a, 12); // or any int/Integer as it's second parameter

Look at the original Method.invoke() method signature - 查看原始的Method.invoke()方法签名-

public Object invoke(Object obj,
            Object... args)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException

And it has no overloaded version. 而且它没有重载版本。 So your method call - m.invoke() is not correct 因此,您的方法调用m.invoke()不正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM