天天看点

Java Annotation详解(二): 反射和Annotation

annotation何时才变得有意义呢? 如果结合反射,取得annotation中设置的全部内容,annotation的意义才会被最大化。

在以下的类中class constructor field method package等类都实现了annotatedelement接口

在接口中有以下重要的方法:

· getannotations(class annotationtype)获取一个指定的annotation类型

· getannotations() 获取所有的annotation

· getdeclaredannotations() 获取声明过的所有annotation

· isannotationpresent(class<? extends annotation> annotationclass)这个annotation是否出现

通过这些方法,配合反射我们就可以在程序运行时拿到注解的内容了,例子如下:

首先定义一个普通的含有内建注释的类:

接下来,我们通过反射取出annotation内容要注意,只有deprecated的annotation的定义范围是runtime范围,所以此时通过反射的话,只能取得一个。

输出:

@java.lang.deprecated()

以上,我们取得的是内建的annotation,接下来,我们自己定义一个annotation:

我们通过retentionpolicy指定了其值为runtime,在运行时有效。

通过反射取得指定的annotation,因为现在唯一设置的内容就是mydefaultannotationreflect。

输出: 

key = baidu

value = www.baidu.com

总结:

annotation在实际的开发中,不管如何使用,其最终肯定结合反射机制,也就是说可以通过annotation设置一些内容到方法上去,已完成特定的功能。

继续阅读