package com.annotation;
import java.lang.annotation.Documented; import java.lang.annotation.ElementType;s import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Description { String value(); }
--------------------------------------------------------------------------------------
package com.annotation;
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Mess { String name();
String book();
} --------------------------------------------------------------------------------------
package com.annotation;
@Description("javaeye,做最棒的软件开发交流社区") public class JavaBook {
@Mess(name = ("姓名:西门吹雪"), book = ("著作:java编程细想")) public String getName() { return "java编程思想讲述了很多设计思想"; } @Mess(name = "姓名:叶孤城", book = "著作:关于OGNL的研究") public String getName2() { return "OGNL是对象图形导航的语言"; }
} class com.annotation.TestAnnotation --------------------------------------------------------------------------------------
package com.annotation;
import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set;
public class TestAnnotation { /** * Annotation的使用实例 */ public static void main(String[] args) throws Exception { String CLASS_NAME = "com.annotation.JavaBook"; Class test = Class.forName(CLASS_NAME); Method[] method = test.getMethods(); boolean flag = test.isAnnotationPresent(Description.class); if(flag) { Description des = (Description)test.getAnnotation(Description.class); System.out.println("描述:"+des.value()); } //把JavaBook这一类有利用到@Mess的全部方法保存到Set中去 Set<Method> set = new HashSet<Method>(); for(int i=0;i<method.length;i++) { boolean otherFlag = method[i].isAnnotationPresent(Mess.class); if(otherFlag) set.add(method[i]); } for(Method m: set) { Mess name = m.getAnnotation(Mess.class); System.out.println(name.name()); System.out.println(name.book()); } }
} |