定义
注解(Annotation)也叫元数据,它是一种代码级别的说明,它是JDK 1.5以及以后版本引入的一个特征,与类、接口、枚举是在同一个层次,它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些数据进行说明,注释
功能
- 编写文档:通过代码里标识元数据生成文档(javadoc生成java文档)
- 代码分析:配合反射获取注解和相关参数(spring 基于注解编程)
- 编译检查:override etc ...
Annotation内部结构
注解本质上是继承Annotation的一个接口,
元注解
元注解用于定义注解的注解,java中有如下元注解:
- @Target
- @Retention
- @Document
- @Inherited
@Target 元注解用于声明注解可以使用的作用域,如果没有使用@Target,则除了TYPE_PARAMETER,其他地方都可以使用该注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
@Retention指定注解的声明周期,默认为CLASS
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented用于声明是否生成javadoc
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Inherited 用于声明查询父类的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
注解属性
在注解接口的中定义的方法即为注解属性其,返回值有如下要求:
- 基本数据类型
- String
- Enum
- Annotation
- 以上类型的数组
自定义和获取注解
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnno {
int age();
String name();
//defaut
String desc() default "test";
TestAnno1 anno();
String[] arrays();
}
public @interface TestAnno1 {
}
@TestAnno(age = 1, name = "a", arrays = {"a", "b"}, anno = @TestAnno1)
public class Test {
public static void main(String[] args) {
TestAnno anno = Test.class.getAnnotation(TestAnno.class);
System.out.println("age: " + anno.age());
System.out.println("name: " + anno.name());
System.out.println("arrays: " + Arrays.toString(anno.arrays()));
}
}
运行结果如下:
age: 1
name: a
arrays: [a, b]