注解属性

注解只有成员变量 (属性), 没有方法.
属性的类型必须为 8 种基本类型 + 类 + 接口 +注解 + 枚举, 以及它们的数组.
属性定义时可以使用 default 指定一个默认值.
属性值不能为 null, 默认值不能为 null, 使用时也不能设置 null.

四个元注解

  • @Retention —— 指明注解保留到什么时候
    • SOURCE —— 只在源代码保留, 编译器将代码转为字节码时丢掉
    • CLASS —— 保留到字节码文件中, 在 JVM 加载字节码文件时丢掉
    • RUNTIME —— 保留到运行时
  • @Target —— 指明注解用在什么位置, 默认为适用于所有类型
  • @Document
  • @Inherited —— 指明子类能否得到父类的注解

@Inherited

参考

  1. @Inherited
  2. public @interface Anno1 {}
  3. public @interface Anno2 {}
  4. @Anno1
  5. @Anno2
  6. public class Father {}
  7. public class Son extends Father{
  8. @Test
  9. public void test1(){
  10. Anno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 != null
  11. Anno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 == null
  12. }
  13. }
  1. @Inherited
  2. public @interface Anno1 {}
  3. @Anno1
  4. public @interface Anno2 {}
  5. @Anno2
  6. public class Demo{
  7. @Test
  8. public void test1(){
  9. Anno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 == null, 找不到元注解
  10. Anno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 != null
  11. }
  12. }
  1. public @interface Anno1 {}
  2. @Anno1
  3. public @interface Anno2 {}
  4. @Anno2
  5. public class Demo{
  6. @Test
  7. public void test1(){
  8. Anno2 anno2 = getClass().getAnnotation(Anno2.class); // anno2 != null
  9. Anno1 anno1 = getClass().getAnnotation(Anno1.class); // anno1 == null
  10. Anno1 anno1 = anno2.annotationType().getAnnotation(Anno1.class); // anno1 != null
  11. }
  12. }