定义注解Annotation
使用@interface
定义注解
例子:
@Retention(RetentionPolicy.RUNTIME)//通常我们自定义的Annotation都是RUNTIME
@Target(ElementType.METHOD, ElementType.FIELD) //定义注解@Report可用在方法或字段上
public @interface Report {
int type() default 0;
}
- 注解的参数类似于无参数的方法,可以用
default
设定一个默认值
元注解meta annotation
元注解是可以用来修饰其他注解的
1. @Target
用来定义Annotation能够被应用在源码的哪些位置、
- 类/接口:
ElementType.TYPE
- 字段:
ElementType.FIELD
- 方法:
ElementType.METHOD
- 构造函数:
ElementType.CONSTRUCTOR
- 方法参数:
ElementType.PARAMETER
2. @Retention
用来定义Annotation的生命周期
- 仅编译期:
RetentionPolicy.SOURCE
- 仅class文件:
RetentionPolicy.CLASS
- 运行期:
RetentionPolicy.RUNTIME
若Retention不存在,则annotation默认为class
3. @Repeatable
用来定义annotation可以重复
经过该注解修饰后,在某个类型的声明处,可以添加多个annotation
4. @Inherited
- 用来定义子类是否可以继承父类定义的annotation
- 仅针对
@Target(ElementType.TYPE)
类型的annotation有效 - 仅针对class的继承,对interface无效
使用自定义注解
- 只讨论如何读取RUNTIME类型的注解
- 反射API
- 判断某个注解是否存在于class/field/method/constructor中:
Class.isAnnotationPresent(Class)
/Field.isAnnotationPresent(Class)
/Method.isAnnotationPresent(Class)
/Constructor.isAnnotationPresent(Class)
- 读取Annotation:
Class.getAnnotation(Class)
/Field.getAnnotation(Class)
/Method.getAnnotation(Class)
/Constructor.getAnnotation(Class)
- 判断某个注解是否存在于class/field/method/constructor中: