package com.wangbiao.test; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * Annotation * @author WangBiao *2013-4-28下午05:32:38 */ public class Test_Annotation { // @Retention:注解的保留位置 // @Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含 // @Retention(RetentionPolicy.CLASS) // // 默认的保留策略,注解会在class字节码文件中存在,但运行时没法得到, // @Retention(RetentionPolicy.RUNTIME) // // 注解会在class字节码文件中存在,在运行时能够经过反射获取到 // // @Target:注解的做用目标 // // @Target(ElementType.TYPE) //接口、类、枚举、注解 // @Target(ElementType.FIELD) //字段、枚举的常量 // @Target(ElementType.METHOD) //方法 // @Target(ElementType.PARAMETER) //方法参数 // @Target(ElementType.CONSTRUCTOR) //构造函数 // @Target(ElementType.LOCAL_VARIABLE)//局部变量 // @Target(ElementType.ANNOTATION_TYPE)//注解 // @Target(ElementType.PACKAGE) ///包 // // @Document:说明该注解将被包含在javadoc中 // // @Inherited:说明子类能够继承父类中的该注解 public static void getAnnotationContent() throws Exception{ Class c=Class.forName("com.wangbiao.test.A"); Method m=c.getMethod("getName"); if(m.isAnnotationPresent(MyAnnotation_third.class)){ MyAnnotation_third an=m.getAnnotation(MyAnnotation_third.class); String name=an.name(); int age=an.age(); System.out.println(name+"-"+age); } } @SuppressWarnings({"unchecked","deprecation"}) public static void main(String[] args) throws Exception { A a=new A(); a.setName("test"); System.out.println(a.getName()); // Class c=Class.forName("com.wangbiao.test.A"); // Method m=c.getMethod("getName"); // Annotation[] as=m.getAnnotations(); // for (Annotation annotation : as) { // System.out.println(annotation); // } getAnnotationContent(); } } @Deprecated @MyAnnotation_first(value={"test","good"}) @MyAnnotation_second(name="test") @MyAnnotation_third(name="test",age=20) class A<T>{ private T name; @Deprecated @MyAnnotation_first(value={"test","good"}) @MyAnnotation_second(name="test") @MyAnnotation_third(name="test",age=20) public T getName() { return name; } public void setName(T name) { this.name = name; } } //注解的保存范围 @Retention(value=RetentionPolicy.RUNTIME) @interface MyAnnotation_first{ public String[] value(); } @interface MyAnnotation_second{ public String name();//必须加一个括号 } //若是Retention不是RetentionPolicy.RUNTIME,则取不到这个annotation @Retention(value=RetentionPolicy.RUNTIME) //@Target(value=ElementType.TYPE)//定义注解的位置 @interface MyAnnotation_third{ public String name() default "zhangsan";//必须加一个括号 public int age() default 20; }