Runnable is used
5 * to create a thread, starting the thread causes the object's
6 * run method to be called in that separately executing
7 * thread.
8 *
9 * The general contract of the method run is that it may
10 * take any action whatsoever.
11 *
12 * @see java.lang.Thread#run()
13 */
14 public abstract void run();
15 }
复制代码
我们进行线程开发中常用的 Runnable 就是一个典型的函数式接口,上面源码可以看到它就被 @FunctionalInterface 注解。
可能有人会疑惑,函数式接口标记有什么用,这个原因是函数式接口可以很容易转换为 Lambda 表达式。这是另外的主题了,有兴趣的同学请自己搜索相关知识点学习。
注解的提取
博文前面的部分讲了注解的基本语法,现在是时候检测我们所学的内容了。
我通过用标签来比作注解,前面的内容是讲怎么写注解,然后贴到哪个地方去,而现在我们要做的工作就是检阅这些标签内容。 形象的比喻就是你把这些注解标签在合适的时候撕下来,然后检阅上面的内容信息。
要想正确检阅注解,离不开一个手段,那就是反射。
注解与反射。
注解通过反射获取。首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解
public boolean isAnnotationPresent(Class extends Annotation> annotationClass) {}
然后通过 getAnnotation() 方法来获取 Annotation 对象。
public A getAnnotation(Class annotationClass) {}
或者是 getAnnotations() 方法。
public Annotation[] getAnnotations() {}
前一种方法返回指定类型的注解,后一种方法返回注解到这个元素上的所有注解。
如果获取到的 Annotation 如果不为 null,则就可以调用它们的属性方法了。比如
复制代码
1 @TestAnnotation()
2 public class Test {
3
4 public static void main(String[] args) {
5
6 boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
7
8 if ( hasAnnotation ) {
9 TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
10
11 System.out.println("id:"+testAnnotation.id());
12 System.out.println("msg:"+testAnnotation.msg());
13 }
14
15 }
16
17 }
程序的运行结果是:
id:-1
msg:
复制代码
这个正是 TestAnnotation 中 id 和 msg 的默认值。
上面的例子中,只是检阅出了注解在类上的注解,其实属性、方法上的注解照样是可以的。同样还是要假手于反射。
复制代码
1 @TestAnnotation(msg="hello")
2 public class Test {
3
4 @Check(value="hi")
5 int a;
6
7
8 @Perform
9 public void testMethod(){}
10
11
12 @SuppressWarnings("deprecation")
13 public void test1(){
14 Hero hero = new Hero();
15 hero.say();
16 hero.speak();
17 }
18
19
20 public static void main(String[] args) {
21
22 boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
23
24 if ( hasAnnotation ) {
25 TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
26 //获取类的注解
27 System.out.println("id:"+testAnnotation.id());
28 System.out.println("msg:"+testAnnotation.msg());
29 }
30
31
32 try {
33 Field a = Test.class.getDeclaredField("a");
34 a.setAccessible(true);
35 //获取一个成员变量上的注解
36 Check check = a.getAnnotation(Check.class);
37
38 if ( check != null ) {
39 System.out.println("check value:"+check.value());
40 }
41
42 Method testMethod = Test.class.getDeclaredMethod("testMethod");
43
44 if ( testMethod != null ) {
45 // 获取方法中的注解
46 Annotation[] ans = testMethod.getAnnotations();
47 for( int i = 0;i < ans.length;i++) {
48 System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName());
49 }
50 }
51 } catch (NoSuchFieldException e) {
52 // TODO Auto-generated catch block
53 e.printStackTrace();
54 System.out.println(e.getMessage());
55 } catch (SecurityException e) {
56 // TODO Auto-generated catch block
57 e.printStackTrace();
58 System.out.println(e.getMessage());
59 } catch (NoSuchMethodException e) {
60 // TODO Auto-generated catch block
61 e.printStackTrace();
62 System.out.println(e.getMessage());
63 }
64
65
66
67 }
68
69 }
70
它们的结果如下
id:-1
msg:hello
check value:hi
method testMethod annotation:Perform
复制代码
需要注意的是,如果一个注解要在运行时被成功提取,那么 @Retention(RetentionPolicy.RUNTIME) 是必须的。
注解的使用场景
我相信博文讲到这里大家都很熟悉了注解,但是有不少同学肯定会问,注解到底有什么用呢?
对啊注解到底有什么用?
我们不妨将目光放到 Java 官方文档上来。
文章开始的时候,我用标签来类比注解。但标签比喻只是我的手段,而不是目的。为的是让大家在初次学习注解时能够不被那些抽象的新概念搞懵。既然现在,我们已经对注解有所了解,我们不妨再仔细阅读官方最严谨的文档。
注解是一系列元数据,它提供数据用来解释程序代码,但是注解并非是所解释的代码本身的一部分。注解对于代码的运行效果没有直接影响。
注解有许多用处,主要如下:
提供信息给编译器: 编译器可以利用注解来探测错误和警告信息
编译阶段时的处理: 软件工具可以用来利用注解信息来生成代码、Html文档或者做其它相应处理。
运行时的处理: 某些注解可以在程序运行的时候接受代码的提取
值得注意的是,注解不是代码本身的一部分。
如果难于理解,可以这样看。标签只是某些人对于其他事物的评价,但是标签不会改变事物本身,标签只是特定人群的手段。所以,注解同样无法改变代码本身,注解只是某些工具的工具。
还是回到官方文档的解释上,注解主要针对的是编译器和其它工具软件(SoftWare tool)。
当开发者使用了Annotation 修饰了类、方法、Field 等成员之后,这些 Annotation 不会自己生效,必须由开发者提供相应的代码来提取并处理 Annotation 信息。这些处理提取和处理 Annotation 的代码统称为 APT(Annotation Processing Tool)。
现在,我们可以给自己答案了,注解有什么用?给谁用?给 编译器或者 APT 用的。
如果,你还是没有搞清楚的话,我亲自写一个好了。
亲手自定义注解完成某个目的
我要写一个测试框架,测试程序员的代码有无明显的异常。
—— 程序员 A : 我写了一个类,它的名字叫做 NoBug,因为它所有的方法都没有错误。
—— 我:自信是好事,不过为了防止意外,让我测试一下如何?
—— 程序员 A: 怎么测试?
—— 我:把你写的代码的方法都加上 @Jiecha 这个注解就好了。
—— 程序员 A: 好的。
复制代码
1 NoBug.java
2
3 package ceshi;
4 import ceshi.Jiecha;
5
6
7 public class NoBug {
8
9 @Jiecha
10 public void suanShu(){
11 System.out.println("1234567890");
12 }
13 @Jiecha
14 public void jiafa(){
15 System.out.println("1+1="+1+1);
16 }
17 @Jiecha
18 public void jiefa(){
19 System.out.println("1-1="+(1-1));
20 }
21 @Jiecha
22 public void chengfa(){
23 System.out.println("3 x 5="+ 3*5);
24 }
25 @Jiecha
26 public void chufa(){
27 System.out.println("6 / 0="+ 6 / 0);
28 }
29
30 public void ziwojieshao(){
31 System.out.println("我写的程序没有 bug!");
32 }
33
34 }
复制代码
上面的代码,有些方法上面运用了 @Jiecha 注解。
这个注解是我写的测试软件框架中定义的注解。
复制代码
1 package ceshi;
2
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5
6 @Retention(RetentionPolicy.RUNTIME)
7 public @interface Jiecha {
8
9 }
复制代码
然后,我再编写一个测试类 TestTool 就可以测试 NoBug 相应的方法了。
复制代码
1 package ceshi;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.lang.reflect.Method;
5
6
7
8 public class TestTool {
9
10 public static void main(String[] args) {
11 // TODO Auto-generated method stub
12
13 NoBug testobj = new NoBug();
14
15 Class clazz = testobj.getClass();
16
17 Method[] method = clazz.getDeclaredMethods();
18 //用来记录测试产生的 log 信息
19 StringBuilder log = new StringBuilder();
20 // 记录异常的次数
21 int errornum = 0;
22
23 for ( Method m: method ) {
24 // 只有被 @Jiecha 标注过的方法才进行测试
25 if ( m.isAnnotationPresent( Jiecha.class )) {
26 try {
27 m.setAccessible(true);
28 m.invoke(testobj, null);
29
30 } catch (E
