Why do I get “object is not an instance of declaring class” when invoking a method using reflection?

廉价感情. 提交于 2019-11-30 07:45:13

问题


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

}

Here is the output:

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)

回答1:


When you invoke a method via reflection, you need to pass the object you are calling the method on as the first parameter to Method#invoke.

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



回答2:


 testParamMethod.invoke("", obj); ///// here getting error

The first parameter to invoke must be the object to invoke it on:

 testParamMethod.invoke(s1, "", obj); 


来源:https://stackoverflow.com/questions/7202988/why-do-i-get-object-is-not-an-instance-of-declaring-class-when-invoking-a-meth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!