1). @Retention

表示需要在什么级别保存该注释信息,用于描述注解的生命周期,也是一个枚举RetentionPoicy来决定的,这个枚举我不列出来了,包括这个注解的具体怎么决定注解的生命周期我也不多讲,因为根据小弟这么多年使用的经验,都是填的RetentionPoicy.RUNTIME,填这个值注解处理器才能通过反色拿到注解信息,实现自己的语义,所以大家都填RetentionPoicy.RUNTIME就可以了,想扩展了解的自行google..

2). @Documented

如果用javadoc生成文档时,想把注解也生成文档,就带这个。(话说老铁们都是怎么写文档的,小弟表示从不写文档... ^_^)

3). @Inherited

@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。注意,@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。

其实这几个注解只有一个有点用,就是@Target,大家稍微注意下就行了。注解不是你想加哪就加哪的。

 

 

 


public class Test {

public static void main(String[] args) {
TestVo testVo = new TestVo();
testVo.setId(11);

reflect(testVo,TestVo.class);

}

private static void reflect(TestVo testVo, Class<?> testVoClass) {
Method[] declaredMethods =
testVoClass.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
TestAnnotation annotation = declaredMethod.getAnnotation(TestAnnotation.class);
if (annotation != null) {
System.out.println("Found Use Case:" + annotation.value() + " "
+ annotation.description());
}

}


}
}


 

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
public String value() default "1";
public String description() default "no description";
}

public class TestVo {
private String masg;
private Integer id;

@TestAnnotation(description = "aaaaaaa")
public Integer getId() {
return id;
}
}
posted on 2019-03-14 14:55  java_zhao  阅读(196)  评论(0编辑  收藏  举报