元注解


  • 定义:写在注解定义上的注解叫(注解是给程序提供信息,写在注解上的注解是给注解提供信息,给信息提供信息的叫元信息)注解。

 一、Target 元注解

  • 作用:告诉你定义的注解可以使用在哪里(类定义上,方法,参数等)使用。不写就是就可以用在所有位置上。

   1.定义

@Target({ ElementType.METHOD, ElementType.PARAMETER })   // 只能写在方法或者参数上
  public @interface Anno06 {
}

  2. 使用

public class test01 {
    @Anno01              //注解写在方法之上,若写在类外便会报错
    public void test() {     
    }
}

二、Retention 元注解

  • 作用:告诉注解信息保留到哪个阶段,如果注释类型声明中不存在 Retention 注释,则保留策略默认为 RetentionPolicy.CLASS
  • 定义了三种情况的枚举:

   ①CLASS:编译器将把注解记录在类文件中,但在运行时 JVM 不需要保留注释。

   ②RUNTIME:编译器将把注解记录在类文件中,在运行时JVM 将保留注解,因此可以反射性地读取。

   ③SOURCE:编译器要丢弃的注解。

    1. 定义

@Retention(RetentionPolicy.SOURCE)      //只在源码中

 @Retention(RetentionPolicy.RUNTIME)      //使用该注解保留到运行前

  public @interface Anno01 {


}

 

   2.反射测试

public class test03 {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        Class clazz=test02.class;
        Method m=clazz.getDeclaredMethod("test");
        System.out.println(m.isAnnotationPresent(Anno01.class));
    }
}

三、Documented元注解

  • 作用:如果一个注解定义时间使用了该元注解,那么产生的javadoc文档就会把注解显示出来。

  1. 定义

@Documented
public @interface Anno10 {
   public String doc();
}

  2. 使用

public class Test20 {
    @Anno10(doc = "我是文档注解")
    public void test() {
    }
}
//然后选中项目,点击Project,选中Generate Javadoc,然后连续点两个next,输入框输入-encoding UTF-8 -charset UTF-8,最后finish生成javadoc文档,将index.html拖入浏览器查看即可

  

四、Inherited 元注解

  • 作用:用于指示子类是否可以继承父类中的注解。

  1.定义注解

@Retention(RetentionPolicy.RUNTIME)    //定义注解1
public @interface Anno01 {

}

  @Inherited                //定义注解2

  @Retention(RetentionPolicy.RUNTIME)

  public @interface Anno02 {

  }

 

  2. 定义父类A和B

@Anno01
@Anno02
public class A {        //定义父类A
}

public class B extends A {      //定义父类B继承父类A
}

  3. 反射查看继承

public class Test {
    public static void main(String[] args) {
        Class clazz=B.class;
        Annotation[] as=clazz.getAnnotations();
          //只输出了@cn.edu.xcu.annotation.v2.Anno02(),说明加上@Inherited才会被继承
        for (Annotation annotation : as) {
            System.out.println(annotation);
        }
    }
}

原文地址:https://www.cnblogs.com/yuanshuai1026/p/11564170.html