[英]Java Reflection call to method with Generic parameters
如何通过反射调用方法,当它具有通用参数时,如下面的片段 -
@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
doSomething
方法是MyTest
class 的一部分。 Method::invoke
必须接受三个参数:
MyTest
class 的实例,将在其上调用该方法。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
}
还要记住 generics 在编译时被擦除。 所以每个泛型类型在运行时都是Object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.