public void doSth(){
}
@MyType(authorName="hadeslee",lastModified="20061207",bugFixes="what")
public void doAnother(){
}
}
加了元数据的类和不加元数据的类差不多,只不过如果你的元数据注释如果是运行时的话,你的类文件可能会比不加元数据大一些,因为它必须把一些注释的信息写入到class文件中去,我们已经注释了我们的类,现在我们来看一下,我们如何去取我们的注释,
/*
* GetAnno.java
*
* Created on 2006年12月7日, 下午3:46
*
* To change this template, choose Tools Template Manager
* and open the template in the editor.
*/
package testAnno;
/**
*
* @author lbf
*/
import java.lang.annotation.*;
import java.lang.reflect.*;
public class GetAnno {
/** Creates a new instance of GetAnno */
public GetAnno() {
}
public static void main(String[] args)throws Exception {
Test1 t=new Test1();
Class c=Test1.class ;
Annotation[] as= c.getDeclaredAnnotations();
for(Annotation an:as){
System.out.println("类Test1的注释"+an);
}
Method med=c.getDeclaredMethod("doSth");
Annotation[] ass=med.getDeclaredAnnotations();
for(Annotation an:ass){
Class<!--/sp-->extends Annotation> clazz=an.annotationType();
Annotation[] ased=clazz.getAnnotations();
for(Annotation ad:ased){
System.out.println("注释的注释:"+ad);
}
System.out.println("方法doSth的注释:"+an);
}
}
}
此程序输出如下
类Test1的注释@testAnno.MyType(bugFixes=ok, authorName=hadeslee, lastModified=20061207)
注释的注释:@java.lang.annotation.Documented()
注释的注释:@java.lang.annotation.Retention(value=RUNTIME)
方法doSth的注释:@java.lang.Deprecated()
注释的注释:@java.lang.annotation.Retention(value=RUNTIME)
注释的注释:@java.lang.annotation.Target(value=[TYPE, METHOD])
方法doSth的注释:@testAnno.MyType(bugFixes=what, authorName=hadeslee, lastModified=20061207)
从这代码里,我们可以看出,取注释其实很简单,就是利用反射机制来取的.不过我们要特别注意到的一点是,我们不但可以取我们定义的类的注释,也可以取注释的注释,我们这里只取到了MyType的注释,其实还可以往下取,在取的过程中,我们可以看到这些元数据注释类都用了哪些注释。
责任编辑:小草