一 代码
class Info{
//给mytoString方法加了2个内建Annotation
@Deprecated
@SuppressWarnings(value = "This is a waring!")
public String mytoString(){
return "hello world";
}
}
class GetAnnotations{
public static void main(String[] args) throws Exception
{
Class<?> cls=Class.forName("Info");
Method toStringMethod=cls.getMethod("mytoString");
//取得全部的注解
Annotation ans[]=toStringMethod.getAnnotations();
for(int i=0;i<ans.length;i++)
{
//获得mytoString方法上的所有Annotation。
System.out.println(ans[i]);
}
}
}
二 运行结果
@java.lang.Deprecated()
三 说明
2个内建的Annotation中只有@Deprecated是RUNTIME类型,所以只输出了Deprecated。
只有定义了@Retention(value=RUNTIME)的Annotation才能在程序运行时被反射机制取得。