注解属性
注解只有成员变量 (属性), 没有方法.
属性的类型必须为 8 种基本类型 + 类 + 接口 +注解 + 枚举, 以及它们的数组.
属性定义时可以使用 default 指定一个默认值.
属性值不能为 null, 默认值不能为 null, 使用时也不能设置 null.
四个元注解
- @Retention —— 指明注解保留到什么时候
- SOURCE —— 只在源代码保留, 编译器将代码转为字节码时丢掉
- CLASS —— 保留到字节码文件中, 在 JVM 加载字节码文件时丢掉
- RUNTIME —— 保留到运行时
- @Target —— 指明注解用在什么位置, 默认为适用于所有类型
- @Document
- @Inherited —— 指明子类能否得到父类的注解
@Inherited
@Inheritedpublic @interface Anno1 {}public @interface Anno2 {}@Anno1@Anno2public class Father {}public class Son extends Father{@Testpublic void test1(){Anno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 != nullAnno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 == null}}
@Inheritedpublic @interface Anno1 {}@Anno1public @interface Anno2 {}@Anno2public class Demo{@Testpublic void test1(){Anno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 == null, 找不到元注解Anno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 != null}}
public @interface Anno1 {}@Anno1public @interface Anno2 {}@Anno2public class Demo{@Testpublic void test1(){Anno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 != nullAnno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 == nullAnno1 anno1 = anno2.annotationType().getAnnotation(Anno1.class); // anno1 != null}}
