一 代码
//定义该自定义注解的保存范围是RUNTIME @Retention(value = RetentionPolicy.RUNTIME) @interface MyAnnotation { public String key(); public String value(); } class Info{ //给mytoString方法定义了3个注解 @Deprecated @SuppressWarnings(value = "This is a waring!") @MyAnnotation(key="one",value = "test") public String mytoString(){ return "hello MyAnnotation"; } } class GetAnnotation{ public static void main(String[] args) throws Exception { Class> cls=Class.forName("Info"); Method toStringMethod=cls.getMethod("mytoString"); //判断该方法上是否有指定类型的注解存在 if(toStringMethod.isAnnotationPresent(MyAnnotation.class)) { //声明MyAnnotation对象 MyAnnotation my=null; my=toStringMethod.getAnnotation(MyAnnotation.class); //获得该注解变量,并打印输出 String key=my.key(); String value=my.value(); System.out.println(key+"->"+value); } } }
二 运行结果
one->test