在java中,我们可以使用4种预先定义的注释对注释定义进行注释,这4种注释是:
n Target:指明注释可以在哪些代码段中使用,以避免对注释的误用。
n Retention:说明编译器在编译和运行时是否忽略该种注释
n Documented:说明注释是否出现在Javadoc中
n Inherited:当我们在一个类中使用了某种注释,有时候会希望将来它的所有子类中都包含有该种注释信息,如果在注释定义中添加了@Inherited,那么这种注释就会被调用者的子类继承
当我们在一个类中使用注释定义了一系列的元数据之后,我们应该如何获取这些元数据呢?我们通过下面的例子来说明。
Annotation的定义仍然使用列出来的两个,因为我们需要在获得类文件中的注释信息,所以必须在注释定义中添加Retention注释。
首先我们定义两个注释,注释Todo说明了还有什么事情需要做:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Todo {
String value();
}
注释Author说明了一个方法或者类的定义者:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
public enum Gender{MALE,FEMALE};
String name();
String email();
Gender gender() default Gender.MALE;
}
然后我们在一个简单的类中添加这两种类型的注释:
public @Todo("delete this class") class Foo {
public void methodA(){}
public @Author(name="B",email="b@Foo.com") void methodB(){
}
public @Author(name="A",email="a@Foo.com") String fieldA;
}
通过下面一段代码我们可以提取相应的元数据:
import java.lang.reflect.Method;
public class GetAnnotations {
public static void main(String[] args) {
try {
Class<?> klass=Class.forName(args[0]);
if(klass.isAnnotationPresent(Todo.class))
{
Todo t=klass.getAnnotation(Todo.class);
System.out.println(t);
}
for(Method m:klass.getMethods())
{
if(m.isAnnotationPresent(Author.class))
{
Author a=m.getAnnotation(Author.class);
System.out.printf("Method:%s,Author:%s%n",m.getName(),a);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
使用下面的命令行运行程序:
java GetAnnotations Foo
运行结果如下:
@Todo(value=delete this class)
Method:methodB,Author:@Author(gender=MALE, name=B,email=b@Foo.com)
联系客服