Java注解之Retention、Documented、Inherited介绍

最近研究多数据源问题,使用的是druid链接池,多数据源经过注解自动配置,使用这三个注解 @Retention @Documented @Inherited 自定义一个注解配置数据源html

Retention注解:- Retention(保留)注解说明,这种类型的注解会被保留到那个阶段java

有三个值:工具

1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略 2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略测试

3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,因此他们能在运行时被JVM或其余使用反射机制的代码所读取和使用. 示例1演示了 RetentionPolicy.RUNTIME 的声明: Java注解的示例1:ui

@Retention(RetentionPolicy.RUNTIME) public @interface TestRetention { .net

    String doTestRetention();htm

} 对象

在这个示例中, @Retention(RetentionPolicy.RUNTIME)注解代表 TestRetention注解将会由虚拟机保留,以便它能够在运行时经过反射读取.blog

Documented 注解:继承

Documented 注解代表这个注解应该被 javadoc工具记录. 默认状况下,javadoc是不包括注解的. 但若是声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 因此注解类型信息也会被包括在生成的文档中. 示例2进一步演示了使用 @Documented:

Java注解的示例2:

@Documented public @interface TestDocumented {

    String doTestDocument();

}

接下来,像下面这样修改TestAnnotations类:

public class TestAnnotations {

    public static void main(String arg[]) {

    new TestAnnotations().doSomeTestRetention();

    new TestAnnotations().doSomeTestDocumented();

}

@TestRetention (doTestRetention="保留注解信息测试")

public void doSomeTestRetention() { System.ou

t.printf("测试注解类型 'Retention'"); }

@Test_Documented(doTestDocument="Hello document")

public void doSomeTestDocumented()

{ System.out.printf("测试注解类型 'Documented'"); } }

如今,若是使用 javadoc命令生成 TestAnnotations.html文件,你将看到相似于图1的结果.

Inherited 注解 这是一个稍微复杂的注解类型. 它指明被注解的类会自动继承. 更具体地说,若是定义注解时使用了 @Inherited 标记,而后用定义的注解来标注另外一个父类, 父类又有一个子类(subclass),则父类的全部属性将被继承到它的子类中. 在示例7中,你会看到使用 @Inherited 标签的好处.

Java注解的示例3

首先,定义你的注解:

@Inherited

public @interface MyParentObject {

    boolean isInherited() default true;

    String doSomething() default "Do what?";

}

接下来,使用注解标注了一个类:

@MyParentObject

public Class MyChildObject { }

正如你看到的,你不须要在实现类中定义接口方法. 由于使用 @Inherited标记,这些都自动继承了. 若是你使用一种古老的方式定义实现类,会是什么样子呢? 看看下面这张 古老的实现方式吧:

public class MyChildObject implements MyParentObject {

    public boolean isInherited() { return false; }

    public String doSomething() { return ""; }

    public boolean equals(Object obj) { return false; }

     public int hashCode() { return 0; }

    public String toString() { return ""; }

     public Class annotationType() { return null; }

 }

看到的区别吗? 能够看到,你必须实现父接口的全部方法.

除了isInherited()和从myParentObject doSomething()方法外,

你还须要实现 java.lang.Object的

equals(),

toString()

和hasCode()方法.

还有 java.lang.annotation.Annotation 类的

annotationType()方法. 无论你是否是想要实现这些方法,你必须在继承的对象中包含这些.

相关文章
相关标签/搜索