Java 注解

定义

注解通过 @interface 关键字进行定义。

public @interface AnnotationTest {

}

应用

创建一个类 Test, 然后在类定义的地方加上 @TestAnnotation 就可以用 TestAnnotation 注解这个类了。

你可以简单理解为将 TestAnnotation 这张标签贴到 Test 这个类上面。

不过,要想注解能够正常工作,还需要介绍一下一个新的概念那就是元注解。

@AnnotationTest()
public class TestAnnotatition {
}

 

元注解

元注解是什么意思呢?

元注解是可以注解到注解上的注解,或者说元注解是一种基本注解,但是它能够应用到其它的注解上面。

如果难于理解的话,你可以这样理解。元注解也是一张标签,但是它是一张特殊的标签,它的作用和目的就是给其他普通的标签进行解释说明的。

元标签有 @Retention、@Documented、@Target、@Inherited、@Repeatable 5 种。

@Retention

Retention 的英文意为保留期的意思。当 @Retention 应用到一个注解上的时候,它解释说明了这个注解的的存活时间。

它的取值如下: 
- RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。 
- RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。 
- RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。

我们可以这样的方式来加深理解,@Retention 去给一张标签解释的时候,它指定了这张标签张贴的时间。@Retention 相当于给一张标签上面盖了一张时间戳,时间戳指明了标签张贴的时间周期。

@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
}

上面的代码中,我们指定 TestAnnotation 可以在程序运行周期被获取到,因此它的生命周期非常的长。

@Documented

顾名思义,这个元注解肯定是和文档有关。它的作用是能够将注解中的元素包含到 Javadoc 中去。

@Target

Target 是目标的意思,@Target 指定了注解运用的地方。

你可以这样理解,当一个注解被 @Target 注解时,这个注解就被限定了运用的场景。

类比到标签,原本标签是你想张贴到哪个地方就到哪个地方,但是因为 @Target 的存在,它张贴的地方就非常具体了,比如只能张贴到方法上、类上、方法参数上等等。@Target 有下面的取值

  • ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
  • ElementType.CONSTRUCTOR 可以给构造方法进行注解
  • ElementType.FIELD 可以给属性进行注解
  • ElementType.LOCAL_VARIABLE 可以给局部变量进行注解
  • ElementType.METHOD 可以给方法进行注解
  • ElementType.PACKAGE 可以给一个包进行注解
  • ElementType.PARAMETER 可以给一个方法内的参数进行注解
  • ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举

@Inherited

Inherited 是继承的意思,但是它并不是说注解本身可以继承,而是说如果一个超类被 @Inherited 注解过的注解进行注解的话,那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。 
说的比较抽象。代码来解释。

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface Test {}

@Test
public class A {}

public class B extends A {}

注解 Test 被 @Inherited 修饰,之后类 A 被 Test 注解,类 B 继承 A, 类 B 也拥有 Test 这个注解。

可以这样理解:

老子非常有钱,所以人们给他贴了一张标签叫做富豪。

老子的儿子长大后,只要没有和老子断绝父子关系,虽然别人没有给他贴标签,但是他自然也是富豪。

老子的孙子长大了,自然也是富豪。

这就是人们口中戏称的富一代,富二代,富三代。虽然叫法不同,好像好多个标签,但其实事情的本质也就是他们有一张共同的标签,也就是老子身上的那张富豪的标签。

@Repeatable

Repeatable 自然是可重复的意思。@Repeatable 是 java 1.8 才加进来的,所以算是一个新的特性。

什么样的注解会多次应用呢?通常是注解的值可以同时取多个。

举个例子,一个人他既是程序员又是产品经理, 同时他还是个画家。


@interface Persons {
    Person[]  value();
}

@Repeatable(Persons.class)
@interface Person{
String role default "";
}

@Person(role="artist")
@Person(role="coder")
@Person(role="PM")
public class SuperMan{

}

注意上面的代码,@Repeatable 注解了 Person。而 @Repeatable 后面括号中的类相当于一个容器注解。

什么是容器注解呢?就是用来存放其它注解的地方。它本身也是一个注解。

我们再看看代码中的相关容器注解。

@interface Persons {
    Person[]  value();
}

按照规定,它里面必须要有一个 value 的属性,属性类型是一个被 @Repeatable 注解过的注解数组,注意它是数组。

如果不好理解的话,可以这样理解。Persons 是一张总的标签,上面贴满了 Person 这种同类型但内容不一样的标签。把 Persons 给一个 SuperMan 贴上,相当于同时给他贴了程序员、产品经理、画家的标签。

我们可能对于 @Person(role=”PM”) 括号里面的内容感兴趣,它其实就是给 Person 这个注解的 role 属性赋值为 PM ,大家不明白正常,马上就讲到注解的属性这一块。

 

注解的属性

注解的属性也叫做成员变量。注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
<span class="hljs-type">int</span> <span class="hljs-title function_">id</span><span class="hljs-params">()</span>;

String <span class="hljs-title function_">msg</span><span class="hljs-params">()</span>;

}

上面代码定义了 TestAnnotation 这个注解中拥有 id 和 msg 两个属性。在使用的时候,我们应该给它们进行赋值。

赋值的方式是在注解的括号内以 value=”” 形式,多个属性之前用 ,隔开。

@TestAnnotation(id=3,msg="hello annotation")
public class Test {

}

需要注意的是,在注解中定义属性时它的类型必须是 8 种基本数据类型外加 类、接口、注解及它们的数组。

注解中属性可以有默认值,默认值需要用 default 关键值指定。比如:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
<span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">id</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> -<span class="hljs-number">1</span>;

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">msg</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">"Hi"</span>;

}

TestAnnotation 中 id 属性默认值为 -1,msg 属性默认值为 Hi。 
它可以这样应用。

@TestAnnotation()
public class Test {}

因为有默认值,所以无需要再在 @TestAnnotation 后面的括号里面进行赋值了,这一步可以省略。

另外,还有一种情况。如果一个注解内仅仅只有一个名字为 value 的属性时,应用这个注解时可以直接接属性值填写到括号内。

public @interface Check {
    String value();
}

上面代码中,Check 这个注解只有 value 这个属性。所以可以这样应用。

@Check("hi")
int a;

这和下面的效果是一样的

@Check(value="hi")
int a;

最后,还需要注意的一种情况是一个注解没有任何属性。比如

public @interface Perform {}

那么在应用这个注解的时候,括号都可以省略。

@Perform
public void testMethod(){}

注解的提取

博文前面的部分讲了注解的基本语法,现在是时候检测我们所学的内容了。

我通过用标签来比作注解,前面的内容是讲怎么写注解,然后贴到哪个地方去,而现在我们要做的工作就是检阅这些标签内容。 形象的比喻就是你把这些注解标签在合适的时候撕下来,然后检阅上面的内容信息。

要想正确检阅注解,离不开一个手段,那就是反射。

注解与反射。

注解通过反射获取。首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}

然后通过 getAnnotation() 方法来获取 Annotation 对象。

 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}

或者是 getAnnotations() 方法。

public Annotation[] getAnnotations() {}

前一种方法返回指定类型的注解,后一种方法返回注解到这个元素上的所有注解。

如果获取到的 Annotation 如果不为 null,则就可以调用它们的属性方法了。比如

@TestAnnotation()
public class Test {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {

    <span class="hljs-type">boolean</span> <span class="hljs-variable">hasAnnotation</span> <span class="hljs-operator">=</span> Test.class.isAnnotationPresent(TestAnnotation.class);

    <span class="hljs-keyword">if</span> ( hasAnnotation ) {
        <span class="hljs-type">TestAnnotation</span> <span class="hljs-variable">testAnnotation</span> <span class="hljs-operator">=</span> Test.class.getAnnotation(TestAnnotation.class);

        System.out.println(<span class="hljs-string">"id:"</span>+testAnnotation.id());
        System.out.println(<span class="hljs-string">"msg:"</span>+testAnnotation.msg());
    }

}

}

程序的运行结果是:

id:-1
msg:

这个正是 TestAnnotation 中 id 和 msg 的默认值。

上面的例子中,只是检阅出了注解在类上的注解,其实属性、方法上的注解照样是可以的。同样还是要假手于反射。@TestAnnotation(msg="hello")

public class Test {
<span class="hljs-annotation">@Check(value=<span class="hljs-string">"hi")
<span class="hljs-keyword">int a;


<span class="hljs-annotation">@Perform
<span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">testMethod(){}

<span class="hljs-annotation">@SuppressWarnings(<span class="hljs-string">"deprecation")
<span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">test1(){
    Hero hero = <span class="hljs-keyword">new Hero();
    hero.say();
    hero.speak();
}


<span class="hljs-keyword">public <span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main(String[] args) {

    <span class="hljs-keyword">boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);

    <span class="hljs-keyword">if ( hasAnnotation ) {
        TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
        <span class="hljs-comment">//获取类的注解
        System.out.println(<span class="hljs-string">"id:"+testAnnotation.id());
        System.out.println(<span class="hljs-string">"msg:"+testAnnotation.msg());
    }


    <span class="hljs-keyword">try {
        Field a = Test.class.getDeclaredField(<span class="hljs-string">"a");
        a.setAccessible(<span class="hljs-keyword">true);
        <span class="hljs-comment">//获取一个成员变量上的注解
        Check check = a.getAnnotation(Check.class);

        <span class="hljs-keyword">if ( check != <span class="hljs-keyword">null ) {
            System.out.println(<span class="hljs-string">"check value:"+check.value());
        }

        Method testMethod = Test.class.getDeclaredMethod(<span class="hljs-string">"testMethod");

        <span class="hljs-keyword">if ( testMethod != <span class="hljs-keyword">null ) {
            <span class="hljs-comment">// 获取方法中的注解
            Annotation[] ans = testMethod.getAnnotations();
            <span class="hljs-keyword">for( <span class="hljs-keyword">int i = <span class="hljs-number">0;i &lt; ans.length;i++) {
                System.out.println(<span class="hljs-string">"method testMethod annotation:"+ans[i].annotationType().getSimpleName());
            }
        }
    } <span class="hljs-keyword">catch (NoSuchFieldException e) {
        <span class="hljs-comment">// TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    } <span class="hljs-keyword">catch (SecurityException e) {
        <span class="hljs-comment">// TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    } <span class="hljs-keyword">catch (NoSuchMethodException e) {
        <span class="hljs-comment">// TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    }



}

}
注解有什么用?

我要写一个测试框架,测试程序员的代码有无明显的异常。

—— 程序员 A : 我写了一个类,它的名字叫做 NoBug,因为它所有的方法都没有错误。 
—— 我:自信是好事,不过为了防止意外,让我测试一下如何? 
—— 程序员 A: 怎么测试? 
—— 我:把你写的代码的方法都加上 @MyTest 这个注解就好了。 
—— 程序员 A: 好的。

 
public class NoBug {
@MyTest
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> suanShu(){
    System.out.println(</span>"1234567890"<span style="color: rgba(0, 0, 0, 1)">);
}
@MyTest
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> jiafa(){
    System.out.println(</span>"1+1="+(1+1<span style="color: rgba(0, 0, 0, 1)">));
}
@MyTest
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> jiefa(){
    System.out.println(</span>"1-1="+(1-1<span style="color: rgba(0, 0, 0, 1)">));
}
@MyTest(a</span>=4,b=5<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> chengfa(<span style="color: rgba(0, 0, 255, 1)">int</span> a,<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> b){  //这里加了参数
    System.out.println(</span>"3 x 5="+ a*<span style="color: rgba(0, 0, 0, 1)">b);
}
@MyTest
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> chufa(){
    System.out.println(</span>"6 / 0="+ 6 / 0<span style="color: rgba(0, 0, 0, 1)">);
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> ziwojieshao(){
    System.out.println(</span>"我写的程序没有 bug!"<span style="color: rgba(0, 0, 0, 1)">);
}

}


MyTest 定义
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {

</span><span style="color: rgba(0, 0, 255, 1)">int</span> a() <span style="color: rgba(0, 0, 255, 1)">default</span> 0<span style="color: rgba(0, 0, 0, 1)">;
</span><span style="color: rgba(0, 0, 255, 1)">int</span> b() <span style="color: rgba(0, 0, 255, 1)">default</span> 0<span style="color: rgba(0, 0, 0, 1)">;

}

 

接下来就是怎么去执行测试了,写一个 Test 类,这里肯定是需要用到反射来获取 annotation 及 annotation 中带的参数

public class TestMyAnnotation {
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> TODO Auto-generated method stub</span>
NoBug testobj = new NoBug();
    Class clazz </span>=<span style="color: rgba(0, 0, 0, 1)"> testobj.getClass();

    Method[] method </span>=<span style="color: rgba(0, 0, 0, 1)"> clazz.getDeclaredMethods();
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">用来记录测试产生的 log 信息</span>
    StringBuilder log = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> StringBuilder();
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 记录异常的次数</span>
    <span style="color: rgba(0, 0, 255, 1)">int</span> errornum = 0<span style="color: rgba(0, 0, 0, 1)">;

    </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> ( Method m: method ) {
        </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 只有被 @MyTest 标注过的方法才进行测试</span>
        <span style="color: rgba(0, 0, 255, 1)">if</span> ( m.isAnnotationPresent( MyTest.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)"> )) {
            </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
                m.setAccessible(</span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">);
                MyTest myTest</span>=m.getAnnotation(MyTest.<span style="color: rgba(0, 0, 255, 1)">class</span>);  <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取方法的annotation</span>
                <span style="color: rgba(0, 0, 255, 1)">if</span>(m.getParameterCount()==2<span style="color: rgba(0, 0, 0, 1)">){

                    m.invoke(testobj, myTest.a(),myTest.b());  </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取annotation的属性,并传参数给invoke</span>
                }<span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{

                    m.invoke(testobj, </span><span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">);

                }


            } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> TODO Auto-generated catch block
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">e.printStackTrace();</span>
                errornum++<span style="color: rgba(0, 0, 0, 1)">;
                log.append(m.getName());
                log.append(</span>" "<span style="color: rgba(0, 0, 0, 1)">);
                log.append(</span>"has error:"<span style="color: rgba(0, 0, 0, 1)">);
                log.append(</span>"\n\r  caused by "<span style="color: rgba(0, 0, 0, 1)">);
                </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">记录测试过程中,发生的异常的名称</span>

log.append(e.getCause().getClass().getSimpleName());
log.append(
"\n\r");
//记录测试过程中,发生的异常的具体信息
log.append(e.getCause().getMessage());
log.append(
"\n\r");
}
}
}

    log.append(clazz.getSimpleName());
    log.append(</span>" has  "<span style="color: rgba(0, 0, 0, 1)">);
    log.append(errornum);
    log.append(</span>" error."<span style="color: rgba(0, 0, 0, 1)">);

    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 生成测试报告</span>

System.out.println(log.toString());

}</span></pre>

 

按照这样的思路, testNG,junit 等注释都是可以按照类似的方式来实现