Java反射对具有通用参数的方法的调用

时间:2019-09-21 05:02:20

标签: java reflection

当具有通用参数(例如波纹管片段)时,如何通过反射调用方法-

@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

1 个答案:

答案 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