从 Java 5 开始,官方开始引入注释机制,程序员们也可以通过自定义注解实现各种需求。
Java 注解是通过反射获取注解内容的;在编译器生成类文件时,注解可被嵌入到字节码中。
- JVM 可保留注解的内容,运行时会获得注解内容
- 类、方法、变量、参数、包都可被标注
- 支持自定义注解
内置注解
1 2 3 4 5 6 7 8 9
| @Override @Deprecated @SuppressWarnings @Retention @Documented @Target @Inherited
@SafeVarargs
|
Since Java 8:
1 2 3
| @Native @FunctionalInterface @Repeatable
|
架构

如上图,1 个 Annotation 和 1 个 RetentionPolicy 关联,和 1 到 n 个 ElementType 关联(图左),有很多实现类(图右)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType(); }
|
1 2 3 4 5 6 7 8 9
| package java.lang.annotation;
public enum RetentionPolicy { SOURCE,
CLASS,
RUNTIME }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package java.lang.annotation;
public enum ElementType { TYPE,
FIELD,
METHOD,
PARAMETER,
CONSTRUCTOR,
LOCAL_VARIABLE,
ANNOTATION_TYPE,
PACKAGE }
|
自定义
1 2 3 4 5 6 7 8
| @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotation { }
|