注解生命周期
| 策略 | 说明 |
| SOURCE | 仅在源码保留,编译后丢弃 |
| CLASS | 编译时保留,运行时丢弃 |
| RUNTIME | 运行时保留,可通过反射读取 |
获取注解的方法
Class clazz = MyClass.class;
MyAnnotation ann = (MyAnnotation) clazz.getAnnotation(MyAnnotation.class);
if (ann != null) {
System.out.println(ann.value());
}
boolean hasAnn = clazz.isAnnotationPresent(MyAnnotation.class);
获取所有注解
Annotation[] annotations = method.getAnnotations();
for (Annotation ann : annotations) {
System.out.println(ann.annotationType().getName());
}
小结
- RUNTIME生命周期才可通过反射获取
- getAnnotation()获取指定注解
- getAnnotations()获取所有注解
- isAnnotationPresent()检查是否存在