CR Sardar
CR Sardar

Reputation: 1018

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

Upvotes: 1

Views: 161

Answers (1)

Michał Krzywański
Michał Krzywański

Reputation: 16910

doSomething method is part of MyTest class. Method::invoke will have to take three parameters :

  • instance of MyTest class on which the method will be invoked.
  • instance of AtomicReference
  • instance of 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. So every generic type is Object at runtime.

Upvotes: 2

Related Questions