1

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

4

1 回答 1

5

您需要先访问address Field.

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

然后就可以得到target注解的字段了

Class clazz = annotation.target();

正如 JB Nizet 所评论的,注释中提供的信息与类相关,而不是与实例相关。

于 2013-07-15T21:23:07.307 回答