注解的作用
- 特殊的注释,可以用代码获取到注解的内容,并根据内容自定义操作
- 例如@Override可以在编译的时候检查是否是重写方法
- 可以利用反射获取到运行时注解的内容,并自定义操作
元注解
- 用来修饰自定义注解的注解
Target
- 表示注解可以作用于(修饰)哪些结构
- ElementType.PACKAGE 可以修饰包
- ElementType.Type 可以修饰类、接口、注解或枚举类型
- ElementType.CONSTRUCTOR 可以修饰构造方法
- ElementType.FIELD 可以修饰属性(成员变量),包括枚举常量
- ElementType.METHOD 可以修饰方法
- ElementType.PAPAMETER 可以修饰参数
- ElementType.LOCAL_VARIABLE 可以修饰局部变量
- ElementType.ANNOTATION_TYPE 可以修饰注解类
Retention
- 表示注解的生命周期
- RetentionPolicy.SOURCE: 只有编译器能使用,不会保存在class文件中
- RetentionPolicy.CLASS: 会保留在 class 文件中,但是运行时无法获取。 这是默认值。
- RetentionPolicy.RUNTIME: 编译器、class文件、运行时均可以获取注解内容,通过反射获取该注解。
Repeatable
- 表示在同一结构上可以存在多个相同注解
Documented
- 表示注解可以被javadoc工具提取并保留
Inherited
- 表示该注解会被子类继承
自定义注解
- 使用元注解来表示自定义注解的一些重要特性
- 可以自定义属性值
package com.annotation;
import java.lang.annotation.*;
import java.lang.reflect.Field;
@AnnotationDemo()
public class AnnotationTest {
@AnnotationDemo(word = "hi")
static int name = 1;
public static void main(String[] args) {
Class cl = AnnotationTest.class;
Annotation[] annotations = cl.getDeclaredAnnotations();
for (Annotation an : annotations) {
if(an instanceof AnnotationDemo) {
AnnotationDemo ant = (AnnotationDemo) an;
System.out.println(ant.word());
}
}
Field[] declaredFields = cl.getDeclaredFields();
for (Field field : declaredFields) {
Annotation[] fieldAnnotations = field.getDeclaredAnnotations();
for (Annotation an : fieldAnnotations) {
if(an instanceof AnnotationDemo) {
AnnotationDemo ant = (AnnotationDemo) an;
System.out.println(ant.word());
}
}
}
}
}
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationDemo {
String word() default "hello";
}