samedi 6 novembre 2021

Java Reflections - Get annotation generic method argument

I am trying to find the type of method argument using Java reflection.

public class ReflectionTest {
    public static void main(String[] args) throws NoSuchMethodException {
        Method method = ReflectionTest.class.getDeclaredMethods()[0];
        Parameter parameter = Arrays.stream(method.getParameters())
                .filter(p -> p.isAnnotationPresent(Emits.class))
                .findFirst()
                .get();
        ParameterizedType parameterizedType = (ParameterizedType)parameter.getParameterizedType();
        Class<?> actualTypeArgument = (Class<?>)parameterizedType.getActualTypeArguments()[0];
        System.out.println(actualTypeArgument);//outputs class Person1
    }

    void getName(@Emits List<Person1> playlistItems) {}

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    @interface Emits { }
}

The above code works perfectly. But when I change the getName method signature to

void getName(@Emits List<Person1<?>> playlistItems) {}

This line would fail

Class<?> actualTypeArgument = (Class<?>)parameterizedType.getActualTypeArguments()[0];

with exception

Exception in thread "main" java.lang.ClassCastException: class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to class java.lang.Class (sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl and java.lang.Class are in module java.base of loader 'bootstrap')
    at reflection.ReflectionTest.main(ReflectionTest.java:25)

Is there any way I can fix this issue? I wasted so many hours with no solution for this issue. Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire