源代码如下
//本程序是P205页面:使用反射来显示与某个方法关联的注解,也可以说是第一个注解的例子程序
import java.lang.annotation.*;
import java.lang.reflect.*;
//an annotation type declaration
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno{
String str();
int val();
}
public class Meta {
//annotate a method
@MyAnno(str="Anno Example",val=100)
public static void myMeth(){
Meta ob=new Meta();
// obtain the anno for this method and display the
//values of the members
try{
//first get a Class obj that represents this class
Class<?> c=ob.getClass();
//now get a method object that rep this method
Method m=c.getMethod("myMeth");
//next gett the anno for this class
MyAnno anno =m.getAnnotation(MyAnno.class);
//finally display the values
System.out.println(anno.str()+""+anno.val());
}catch (NoSuchMethodException exc){
System.out.println("Mehtod Not Found.");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
myMeth();
}
}