源代码如下:
import java.lang.annotation.*;
import java.lang.reflect.*;
//an annotation type declaration
//注意本例子是原书第206页面:第二个反射示例的具体代码,为了不和下面的获取所有注解冲突,类命名为 Meta3
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno3{
String str();
int val();
}
public class Meta3 {
//annotate a method
//myMeth now has two arguments
@MyAnno3(str="Two Parameters",val=19)
public static void myMeth(String str,int i){
Meta3 ob=new Meta3();
try{
//first get a Class obj that represents this class
Class<?> c=ob.getClass();
//Here ,the parameter types are specified
Method m=c.getMethod("myMeth",String.class,int.class);
//next get the anno for this class
MyAnno3 anno =m.getAnnotation(MyAnno3.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("test",10);
}
}
本文介绍了一个使用Java反射和注解的示例程序。该程序定义了一个名为`MyAnno3`的注解,并通过反射获取了带有此注解的方法`myMeth`的相关信息。文章展示了如何创建注解、在方法上应用注解以及如何通过反射来读取这些注解。
3120

被折叠的 条评论
为什么被折叠?



