简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM