为什么我得到“对象不是声明类的实例”使用反射调用方法时? [英] Why do I get "object is not an instance of declaring class" when invoking a method using reflection?
本文介绍了为什么我得到“对象不是声明类的实例”使用反射调用方法时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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)
推荐答案
当您通过反射调用方法时,需要将调用方法的对象作为第一个参数传递给方法#incoke
。
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);
这篇关于为什么我得到“对象不是声明类的实例”使用反射调用方法时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文