「java.lang.annotation.Annotation」接口中有这么一句话,用来描述『注解』。
The common interface extended by all annotation types
所有的注解类型都继承自这个普通的接口(Annotation)
这句话有点抽象,但却说出了注解的本质。我们看一个 JDK 内置注解的定义:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
这是注解 @Override 的定义,其实它本质上就是:
public interface Override extends Annotation{
}
没错,注解的本质就是一个继承了 Annotation 接口的接口。有关这一点,你可以去反编译任意一个注解类,你会得到结果的。
一个注解准确意义上来说,只不过是一种特殊的注释而已,如果没有解析它的代码,它可能连注释都不如。
解析一个类或者方法的注解往往有两种形式,一种是编译期直接的扫描,一种是运行期反射。
『元注解』是用于修饰注解的注解,通常用在注解的定义上。
JAVA 中有以下几个『元注解』:
1. @Target
@Target 注解指明该注解可以作用哪些对象上。
@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();
}
注解接收一个ElementType数组,ElementType是一个枚举,成员如下:
2. @Retention
@Retention 用于指明当前注解的生命周期
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
注解接收一个RetentionPolicy数据,RetentionPolicy是个枚举,成员如下:
定义一个注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnnotation {
String value() default "Hello annotation!";
}
使用这个注解:
public class UseAnnotation {
@HelloAnnotation
public void hello() {
System.out.println("hello");
}
@HelloAnnotation("Hello world!")
public void helloWorld() {
System.out.println("Hello world!");
}
}
注解最重要的部分在于对注解的处理。注解处理器就是通过反射机制获取被检查方法上的注解信息,然后根据注解元素的值进行特定的处理。如果没有注解处理器,注解就是个注释,或者连注释都不如。
处理这个注解:
public class Test {
public static void main(String[] args) {
testAnnotation(UseAnnotation.class);
}
private static void testAnnotation(Class> cl) {
for (Method m : cl.getDeclaredMethods()) {
HelloAnnotation ha = m.getAnnotation(HelloAnnotation.class);
if (ha != null) {
System.out.println("Found My Annotation: " + ha.value());
}
}
}
}
输出结果:
Found My Annotation: Hello annotation!
Found My Annotation: Hello world!