简体   繁体   English

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

[英]Java Reflection call to method with Generic parameters

How to call a method through a Reflection, when it has a generic parameter, like bellow snippet -如何通过反射调用方法,当它具有通用参数时,如下面的片段 -

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

It gives me -它给了我-

java.lang.IllegalArgumentException: object is not an instance of declaring class

doSomething method is part of MyTest class. doSomething方法是MyTest class 的一部分。 Method::invoke will have to take three parameters: Method::invoke必须接受三个参数:

  • instance of MyTest class on which the method will be invoked. MyTest class 的实例,将在其上调用该方法。
  • instance of AtomicReference AtomicReference的实例
  • instance of ClassB B 类的ClassB

So it should look like this:所以它应该是这样的:

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
}

Also keep in mind that generics are erased at compile time.还要记住 generics 在编译时被擦除。 So every generic type is Object at runtime.所以每个泛型类型在运行时都是Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM