java 注解

java.lang.annotation 包
Annotation 的基本原则:Annotation 不能影响程序代码的执行,无论增加、删除 Annotation,代码都始终如一的执行
元注解:负责注解其他的注解
@Documented
@Inherited
@Retention
@Target
-------------------------------------------------------------------------------
@Target
用于描述 Annotatiion 的范围
取值有:
java.lang.annotation.ElementType
TYPE:类,接口(包括注解),枚举
FIELD:域(包括枚举常量)
METHOD:方法
PARAMETER:参数
CONSTRUCTOR:构造方法
LOCAL_VARIABLE:局部变量
ANNOTATION_TYPE:注解类型
PACKAGE:包
例子:

@Target(ElementType.TYPE)
public String className();
public @interface TargetTest {
}

 


*******************************************************************************
@Retention
用于描述 Annotation 的生命周期
取值有:
java.lang.annotation.RetentionPolicy
SOURCE:源文件有效
CLASS:在 Class 文件中有效
RUNTIME:在运行时有效,可通过反射获取内容
例子:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnonitionTargetTest {
}

 


*******************************************************************************
@Documented
用于描述 Annotation 被 JavaDoc
例子:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@@Documented 则
public @interface AnnonitionTargetTest {
}

 


生成 javaDoc 后调用 @AnnonitionTargetTest 的类、方法等会出现 @AnnonitionTargetTest,如果没有 @Documented 则调用 @AnnonitionTargetTest 的类、方法等不会出现 @AnnonitionTargetTest
*******************************************************************************
@Inherited
用于描述 Annotation 可以被继承
如果一个使用了 @Inherited 修饰的 annotation 类型被用于一个 class,则这个 annotation 将被用于该 class 的子类。
注意:@Inherited annotation 类型是被标注过的 class 的子类所继承。不从接口继承 annotation,方法并不从重载的方法继承 annotation
例子:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface AnnonitionTargetTest {
}

 


*******************************************************************************
自定义注解
格式:
public @interface 注解名 {定义体}
注解参数的可支持数据类型:
1. 所有基本数据类型
2.String 类型
3.Class 类型
4.enum 类型
5.Annotation 类型
6. 以上所有类型的数组
访问修饰符只有 public 和 default
如果只有一个参数成员, 最好把参数名称设为 "value", 后加小括号
*******************************************************************************
注解处理器类:java.lang.reflect.AnnotatedElement
它的实现类:
java.lang.Class 类,java.lang.reflect.Filed 类,java.lang.reflect.Constructor 类,java.lang.reflect.Method 类,java.lang.Package 类
<T extends Annotation> T getAnnotation(Class<T> annotationClass); 返回改程序元素上存在的、指定类型的注解,如果该类型注解不存在,则返回 null。
Annotation[] getAnnotations(); 返回该程序元素上存在的所有注解。
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); 判断该程序元素上是否包含指定类型的注解,存在则返回 true,否则返回 false.
Annotation[] getDeclaredAnnotations(); 返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。
*******************************************************************************

图片来源于网络