元注解自定义注解处理注解
元注解@Target
使用@Target可以定义Annotation能够被应用于源码的哪些位置,若可用在方法或字段上,可以把@Target注解参数变为数组{ ElementType.METHOD, ElementType.FIELD }
类或接口:ElementType.TYPE; 字段:ElementType.FIELD; 方法:ElementType.METHOD; 构造方法:ElementType.CONSTRUCTOR; 方法参数:ElementType.PARAMETER
@Retention
@Retention定义了Annotation的生命周期
仅编译期:RetentionPolicy.SOURCE; 仅class文件:RetentionPolicy.CLASS; 运行期:RetentionPolicy.RUNTIME
如果@Retention不存在,则该Annotation默认为CLASS。因为通常我们自定义的Annotation都是RUNTIME,所以,务必要加上@Retention(RetentionPolicy.RUNTIME)这个元注解
@Inherited
使用@Inherited定义子类是否可继承父类定义的Annotation。@Inherited仅针对@Target(ElementType.TYPE)类型的annotation有效,并且仅针对class的继承,对interface的继承无效
@Repeatable
使用@Repeatable这个元注解可以定义Annotation是否可重复,经过@Repeatable修饰后,在某个类型声明处,就可以添加多个@Report注解
自定义注解用@interface定义注解添加参数,默认值,核心参数使用value名称添加元注解,其中必须设置@Target和@Retention
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAn {
int type() default 0;
String level() default "info";
String value() default "";
}
处理注解
Java提供的使用反射API读取Annotation的方法
使用反射API读取Annotation: Class.getAnnotation(Class) Field.getAnnotation(Class) Method.getAnnotation(Class) Constructor.getAnnotation(Class)
// 判断@Report是否存在于Person类: Person.class.isAnnotationPresent(Report.class);



