Java注解基本介绍 二

上篇文章我们分析了两种元注解,@Target和@Retention

除了这两种元注解,Java中还提供了另外三种元注解,@Documented、@Inherited和@Repeatable。

下面我们继续分析这三个元注解:

@Documented,被该注解修饰的元素会生成到javadoc中

@DocumentedTest1
@DocumentedTest2
public class Student {
    @Deprecated  //Java内置注解,用于标识方法过期不建议使用
    @SuppressWarnings("uncheck") //忽略警告标识
    public static void read() {
    }
    @Test  // 使用@Test注解修饰的方法
    public void write() { read(); }
}
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentedTest1 {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentedTest2 {
}

使用javadoc命令生成doc文档

javadoc DocumentedTest1.java DocumentedTest2.java Student.java

效果图如下,可以看到@DocumentedTest1注解被生成到了Student类上

Java注解基本介绍 二

使用了@Documented元注解定义的注解生成了JavaDoc文档,没有使用@Documented元注解的注解则没有生成doc文档,这个就是元注解的作用

@Inherited元注解,可以让注解被继承,但不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用getAnnotations()获取父类被@Inherited修饰的注解,下面是一个简单的例子:

我们在上面的DocumentedTest1注解中添加元注解@Inherited

@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentedTest1 {
}
@DocumentedTest1
class A { }
class B extends A { }
@DocumentedTest2
class C { }
class D extends C { }
public class DocumentDemo {
    public static void main(String[] args) {
        A testA = new B();
        System.out.println(Arrays.toString(testA.getClass().getAnnotations()));
        C testC = new D();
        System.out.println(Arrays.toString(testC.getClass().getAnnotations()));
    }
}
/**
 * 运行结果:
 *  [@com.craig.DocumentedTest1()]
 *  []
 */
(0)
上一篇 2019-05-20 18:46
下一篇 2019-06-07 16:01

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注