Annotation的一般形式是 :
- public @interface MyAnnotation {
- String value() default "hahaha";
- }
我认为和它等价的java类为: Annotation的使用方法和Bean的比较:
- public class MyAnnotation extends java.lang.annotation.Annotation{
- private String value = "hahaha";
- public void setValue(String value){
- this.value = value;
- }
- public String getValue(){
- return value;
- }
- }
- @MyAnnotation(value="hello") //对应Bean的set方法
- Method method = AnnotationTest.class.getMethod("doSomthing", null); //取得被注释的方法,AnnotationTest.class为该方法所在的类
- MyRetention mr = method.getAnnotation(MyRetention.class); //取得注释对象
- String value = mr.value(); //取得value的值,对应Bean的get方法.
- public enum RetentionPolicy {
- SOURCE, // 编译器处理完Annotation后不存储在class中
- CLASS, // 编译器把Annotation存储在class中,这是默认值
- RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要
- }
- public enum ElementType {
- TYPE, // 指定适用点为 class, interface, enum
- FIELD, // 指定适用点为 field
- METHOD, // 指定适用点为 method
- PARAMETER, // 指定适用点为 method 的 parameter
- CONSTRUCTOR, // 指定适用点为 constructor
- LOCAL_VARIABLE, // 指定使用点为 局部变量
- ANNOTATION_TYPE, //指定适用点为 annotation 类型
- PACKAGE // 指定适用点为 package
- }
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Documented //这个Annotation可以被写入javadoc
- @Inherited //这个Annotation 可以被继承
- @Target({ElementType.CONSTRUCTOR,ElementType.METHOD}) //表示这个Annotation只能用于注释 构造子和方法
- @Retention(RetentionPolicy.CLASS) //表示这个Annotation存入class但vm不读取
- public @interface MyAnnotation {
- String value() default "hahaha";
- }
Class、Constructor、Field、Method、Package等都实现了该接口,可以通过这些方法访问Annotation信息,前提是要访问的Annotation指定Retention为RUNTIME.