kaqqao kaqqao - 1 month ago 10
Java Question

Is there something like TypeToken for AnnotatedTypes

Since there's no type literals in Java,

TypeToken
trick is commonly used instead.
Say, you want to get a
Type
instance representing
List<String>
, you'd do:

new TypeToken<List<String>>(){}.getType()


Now, I wonder if similar trickery is possible to get an instance of an
AnnotatedType
. For example, to represent
List<@NonNull String>
or even
@NonNull List<@NonNull String>
.

EDIT:
Here's a full
AnnotatedType
-enabled
TypeToken
implementation
.

Answer

Just create a type token - or any anonymous subclass with annotated type parameters - with the annotations and then use reflection to extract the annotated types.

Note that this only works for annotations with runtime retention.

Using the fullType() method from the linked answer:

    List<?> token = new ArrayList<@NonNull String>() {};
    fullType("", token.getClass().getAnnotatedSuperclass());

prints

java.util.ArrayList
<
    @org.checkerframework.checker.nullness.qual.NonNull()
    java.lang.String
>
Comments