Java自定义注解

1. 自定义注解

//表示适用于方法或类
@Target({ElementType.METHOD,ElementType.TYPE})
//运行时注解
@Retention(RetentionPolicy.RUNTIME)
public @interface Description {
    String value();
    int age() default 18;
}

2. 使用注解

@Description(value = "i am class annotation",age=12)
public class Child {
//age采用default值
@Description(value = "i am method annotation")
public String name(){
return null;
}
public int age(){
return 0;
}
}

3. 测试


public class Main {
public static void main(String[] args){
//RetentionPolicy.CLASS或RetentionPolicy.SOURCE时无输出
try{
Class c = new Child().getClass();
boolean isExist = c.isAnnotationPresent(Description.class);
if(isExist){
Description d = (Description) c.getAnnotation(Description.class);
System.out.println(d.value());
System.out.println(d.age());
}
for(Method m : c.getMethods()){
for(Annotation a : m.getAnnotations()){
if(a instanceof Description){
Description d = (Description) a;
System.out.println((d.value()));
System.out.println((d.age()));
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
i am class annotation
12
i am method annotation
18

 

posted @ 2018-12-19 23:18  远去的列车  阅读(204)  评论(0编辑  收藏  举报