DodoFXP
DodoFXP

Reputation: 483

How to get annotations of field in Java

I have my own Annotation

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Template {
   Class target();
}

This Annotation is used in a simple POJO:

public class Something {   
    @JsonSerialize(using = TemplateSerializer.class)
    @Template(target = PersonRepresentation.class)
    private TemplateFoo address = new TemplateFoo() {};
}

And I have Jackson seriliazer TemplateSerializer that gets 'address' passed when serializing the object to JSON.

I wonder how I can get the @Template Annotation given the 'address' instance? I'd like to gets its 'target' field and then inspect the PersonRepresentation.class

Upvotes: 1

Views: 3173

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279930

You need to first access the address Field.

Field address = Something.class.getField("address");
Template annotation = address.getAnnotation(Template.class);

Then you can get the target field of the annotation

Class clazz = annotation.target();

As JB Nizet has commented, the information provided in an Annotation is relevant to the class, not the the instance.

Upvotes: 5

Related Questions