1.
*
元注解有:
@Target,@Retention,@Documented,@Inherited
2.
*
3.
* @Target
表示该注解用于什么地方,可能的
ElemenetType
参数包括:
4.
* ElemenetType.CONSTRUCTOR
构造器声明
5.
* ElemenetType.FIELD
域声明(包括
enum
实例)
6.
* ElemenetType.LOCAL_VARIABLE
局部变量声明
7.
* ElemenetType.METHOD
方法声明
8.
* ElemenetType.PACKAGE
包声明
9.
* ElemenetType.PARAMETER
参数声明
10.
* ElemenetType.TYPE
类,接口(包括注解类型)或
enum
声明
11.
*
12.
* @Retention
表示在什么级别保存该注解信息。可选的
RetentionPolicy
参数包括:
13.
* RetentionPolicy.SOURCE
注解将被编译器丢弃
14.
* RetentionPolicy.CLASS
注解在
class
文件中可用,但会被
VM
丢弃
15.
* RetentionPolicy.RUNTIME VM
将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
16.
*
17.
* @Documented
将此注解包含在
javadoc
中
18.
*
19.
* @Inherited
允许子类继承父类中的注解
|
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// 将此注解包含在 javadoc 中 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(value="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()); } } }