| package lighter.javaeye.com; 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.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Description { String value(); } |
| package lighter.javaeye.com; 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与@Description里的不同,参数成员也不同 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Name { String originate(); String community(); } |
| package lighter.javaeye.com; @Description("javaeye,做最棒的软件开发交流社区") public class JavaEyer { @Name(originate="创始人:robbin",community="javaEye") public String getName() { return null; } @Name(originate="创始人:江南白衣",community="springside") public String getName2() { return "借用两位的id一用,写这一个例子,请见谅!"; } } |
| package lighter.javaeye.com; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class TestAnnotation { /** * author lighter * 说明:具体关天Annotation的API的用法请参见javaDoc文档 */ public static void main(String[] args) throws Exception { String CLASS_NAME = "lighter.javaeye.com.JavaEyer"; 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()); System.out.println("-----------------"); } //把JavaEyer这一类有利用到@Name的全部方法保存到Set中去 Set<Method> set = new HashSet<Method>(); for(int i=0;i<method.length;i++) { boolean otherFlag = method[i].isAnnotationPresent(Name.class); if(otherFlag) set.add(method[i]); } for(Method m: set) { Name name = m.getAnnotation(Name.class); System.out.println(name.originate()); System.out.println("创建的社区:"+name.community()); } } } |