jeudi 28 janvier 2021

How to get annotation used on inner generic type?

My question is somewhat a little more advanced reflection problem.

Suppose you have a class:

import java.util.List;

public class Sample
{

    private List<@First List<@Second String>> field;

}

As you see, type of field is List<List<String>>. Assume you have 2 different annotations: @First and @Second. These annotations are put on this field's generic type, respectively. Now, my goal is to access these both annotations at runtime.

Here is my code:

Field field = Sample.class.getDeclaredField("field");
AnnotatedType annotatedType = field.getAnnotatedType();
AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) annotatedType;

When I invoke getAnnotatedType() on field, it returns me an AnnotatedParameterizedType.

AnnotatedType annotatedActualTypeArgument = annotatedParameterizedType.getAnnotatedActualTypeArguments()[0];
Annotation firstAnnotation = annotatedActualTypeArgument.getAnnotations()[0];

getAnnotatedActualTypeArguments() method actually gives me the @First annnotation.

ParameterizedType innerType = (ParameterizedType) annotatedActualTypeArgument.getType();

However, when I try to get type of the inner generic argument, it gives me a ParameterizedType. Which correctly defines the type of inner-most argument: List<String>. But, because it is not of type AnnotatedParameterizedType, I cannot access @Second annotation.

Is there any way I can access the second annotation as well at runtime?





Aucun commentaire:

Enregistrer un commentaire