java - 为什么在使用反射调用方法时得到 "object is not an instance of declaring class"?

标签 java reflection illegalargumentexception

public class Shared {

    public static void main(String arg[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        Shared s1 = new Shared();

        Object obj[] = new Object[2];
        obj[0] = "object1";
        obj[1] = "object2";
        s1.testParam(null, obj);

        Class param[] = new Class[2];
        param[0] = String.class;
        param[1] = Object[].class; //// how to define the second parameter as array
        Method testParamMethod = s1.getClass().getDeclaredMethod("testParam", param);
        testParamMethod.invoke("", obj); ///// here getting error
    }

    public void testParam(String query,Object ... params){
        System.out.println("in the testparam method");
    }

}

这是输出:

in the testparam method
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at pkg.Shared.main(Shared.java:20)

最佳答案

当您通过反射调用方法时,您需要将调用该方法的对象作为第一个参数传递给 Method#invoke

// equivalent to s1.testParam("", obj)
testParamMethod.invoke(s1, "", obj);

关于java - 为什么在使用反射调用方法时得到 "object is not an instance of declaring class"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7202988/

相关文章:

java - 如何在 'if' 条件下自动处理 IllegalArgumentException

java - Maven 属性问题

当字段为 JTextfield 时 java.lang.reflect.field getText

c# - 从派生自基类的程序集中获取所有类型

c# - 反射找不到嵌套类型的 protected 字段

java - 在 Java 中处理 Not Acceptable 方法参数的最佳方法是什么?

java - Amazon Web Service DynamoDB 错误 com.amazonaws.auth.AWSCredentials

java - 我正在尝试检查某些文件是否存在。为什么我的程序不允许用户输入文件?

java - 为什么我不能对 Annotation 的引用使用 getAnnotation()?

java - 使用记事本在java中播放.mp3文件