RetentionPolicy用于修饰注解能否被JVM所读取

来源:互联网 发布:淘宝有好货写手 编辑:程序博客网 时间:2024/06/08 17:36
import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Retention;@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation{String hello() default "mylove";String world();}@MyAnnotation(hello="beijing",world="shanghai")//注解用语修饰类本身public class MyTest{@MyAnnotation(hello="nanjing",world="chengdu")@Deprecated@SuppressWarnings("unchecked")public void output(){System.out.println("output something");}}  import java.lang.reflect.*;import java.lang.annotation.*;public class MyReflection{public static void main(String args[])throws Exception{MyTest mytest=new MyTest();Class<MyTest> classType=MyTest.class;Method method=classType.getMethod("output",new Class[]{});if(method.isAnnotationPresent(MyAnnotation.class)){method.invoke(mytest,new Object[]{});MyAnnotation myannotation=method.getAnnotation(MyAnnotation.class);String hello=myannotation.hello();String world=myannotation.world();System.out.println(hello+" , "+world);}Annotation [] annotations=method.getAnnotations();for(Annotation annotation:annotations){System.out.println(annotation.annotationType().getName());}}}

0 0
原创粉丝点击