当具有通用参数(例如波纹管片段)时,如何通过反射调用方法-
@Test
public void testOptional() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException
{
AtomicReference<ClassA> atomicReference = new AtomicReference<>(new ClassA());
ClassB classB = new ClassB();
Method method = MyTest.class.getDeclaredMethod("doSomething", AtomicReference.class, ClassB.class);
method.setAccessible(true);
method.invoke(atomicReference, classB);
}
private void doSomething(AtomicReference<ClassA> classA, ClassB classB){
System.out.println("Hi do not poke me, I am working!");
}
它给了我-
java.lang.IllegalArgumentException: object is not an instance of declaring class
答案 0 :(得分:2)
doSomething
方法是MyTest
类的一部分。 Method::invoke
必须采用三个参数:
MyTest
类的实例。AtomicReference
的实例ClassB
的实例所以它应该看起来像这样:
public void testOptional() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException, InvocationTargetException {
AtomicReference<ClassA> atomicReference = new AtomicReference<>(new ClassA());
ClassB classB = new ClassB();
MyTest myTest = new MyTest(); // here we create the object
Method method = MyTest.class.getDeclaredMethod("doSomething", AtomicReference.class, ClassB.class);
method.setAccessible(true);
method.invoke(myTest, atomicReference, classB); //we invoke doSomething on myTest object with parameters
}
还请记住,泛型会在编译时删除。因此,每个通用类型在运行时都是Object
。