源代码如下:
//show all annotations for a class and a method
import java.lang.annotation.*;
import java.lang.reflect.*;
//
//注意本例子是原书第207页面:获取所有注解的代码。
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno2{
String str();
int val();
}
@Retention(RetentionPolicy.RUNTIME)
@interface What{
String description();
}
@What(description="An annotation test class")
@MyAnno2(str="Meta2",val=99)
public class Meta2 {
@What(description="An annotation test method")
@MyAnno2(str="Testing method",val=100)
public static void myMeth(){
Meta2 ob=new Meta2();
try{
Annotation annos[]=ob.getClass().getAnnotations();
//display all anno for Meta2
System.out.println("All annos for Meta2:");
for(Annotation a:annos)
System.out.println(a);
System.out.println();
//display all annos for myMeth.
Method m=ob.getClass().getMethod("myMeth" );
annos=m.getAnnotations();
System.out.println("All annos for myMeth:");
for(Annotation a : annos)
System.out.println(a);
}catch (NoSuchMethodException exc){
System.out.println("Mehtod Not Found.");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
myMeth();
}
}