java 自定义注解

1). @Retentionjava

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

2). @Documentedspa

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

3). @Inherited接口

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

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

 

 

 


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;    }}
相关文章
相关标签/搜索