1 @Documented//拥有这个注解的元素可以被javadoc文档化 2 @Target(ElementType.METHOD) 3 //该注解可以注解的程序元素返回,不添加则表示可以注解任何程序元素 4 @Inherited//该注解类型被自动继承 5 @Retention(RetentionPolicy.RUNTIME) 6 //指明该注解被保留的时间长短 7 public @interface InfoMethod { 8 String author() default "sookie" ; 9 String date(); 10 int version() default 1; 11 String comments(); 12 }
public class Test { @Override @InfoMethod(author= "22",comments="Main method",date="2016-02-04") //存在默认值的注解方法,使用时可以不传值,其余都要传值 public String toString(){ return "Overriden toString method" ; } @Deprecated @InfoMethod(author= "33",comments="Deprecated method",date="2016-02-16") public static void oldMethod (){ System. out.println("该方法已过时" ); } @SuppressWarnings({ "unchecked", "rawtypes" }) @InfoMethod(comments= "SuppressWarnings method",date="2016-02-16") public static void genericsTest(){ List list = new ArrayList(); list.add( "OK"); oldMethod(); } }
public static void main(String[] args) throws Exception{ Class<Test> cls = (Class<Test>) Test. class; for(Method method : cls.getDeclaredMethods()){ //获取到该类中的所有方法(不包括继承的)并执行遍历 if(method.isAnnotationPresent(InfoMethod.class)){ //如果指定类型的注解存在于此元素上 for(Annotation anno : method.getAnnotations()){ System.out.println(method.getName()+"方法上的注解有" +anno); } InfoMethod methodAnno = method.getAnnotation(InfoMethod.class); //获取到该方法上的InfoMethod注解对象 System.out.println("--author:" +methodAnno.author()); System.out.println("--date:" +methodAnno.date()); System.out.println("--comments:" +methodAnno.comments()); } } }
原文:http://www.cnblogs.com/programInit/p/6363115.html