Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access Java 8 type information at runtime?

Assuming I have the following member in a class which makes use of Java 8 type annotations:

private List<@Email String> emailAddresses;

Is it possible to read the @Email annotation given on the String type use at runtime using reflection? If so, how would this be done?

Update: That's the definition of the annotation type:

@Target(value=ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Email {}
like image 459
Gunnar Avatar asked Mar 13 '14 09:03

Gunnar


People also ask

What is runtime type java?

Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.

What is type information in Java?

There are two types of data types in Java: Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.


1 Answers

Yes it is possible. The reflection type representing this kind of structure is called AnnotatedParameterizedType. Here is an example of how to get your annotation:

// get the email field 
Field emailAddressField = MyClass.class.getDeclaredField("emailAddresses");

// the field's type is both parameterized and annotated,
// cast it to the right type representation
AnnotatedParameterizedType annotatedParameterizedType =
        (AnnotatedParameterizedType) emailAddressField.getAnnotatedType();

// get all type parameters
AnnotatedType[] annotatedActualTypeArguments = 
        annotatedParameterizedType.getAnnotatedActualTypeArguments();

// the String parameter which contains the annotation
AnnotatedType stringParameterType = annotatedActualTypeArguments[0];

// The actual annotation
Annotation emailAnnotation = stringParameterType.getAnnotations()[0]; 

System.out.println(emailAnnotation);  // @Email()
like image 56
kapex Avatar answered Sep 23 '22 16:09

kapex