Java1.5中的annotation简介

转载自:http://www.blogjava.net/livery/articles/203096.html

1、Target
指定所定义的annotation可以用在哪些程序单元上
如果Target没有指定,则表示该annotation可以使用在任意程序单元上
代码
    @Target({ElementType.ANNOTATION_TYPE,
             ElementType.CONSTRUCTOR,
             ElementType.FIELD,
            ElementType.LOCAL_VARIABLE,
             ElementType.METHOD,
             ElementType.PACKAGE,
             ElementType.PARAMETER,
             ElementType.TYPE})
    public @interface TODO {}


2 、Retention
指出Java编译期如何对待annotation
annotation可以被编译期丢掉,或者保留在编译过的class文件中
在annotation被保留时,它也指定是否会在JVM加载class时读取该annotation
代码
   @Retention(RetentionPolicy.SOURCE)  // Annotation会被编译期丢弃
   public @interface TODO1 {}
   @Retention(RetentionPolicy.CLASS)   // Annotation保留在class文件中,但会被JVM忽略
   public @interface TODO2 {}
   @Retention(RetentionPolicy.RUNTIME) // Annotation保留在class文件中且会被JVM读取
   public @interface TODO3 {}


3 、Documented
指出被定义的annotation被视为所熟悉的程序单元的公开API之一
被@Documented标注的annotation会在javadoc中显示,这在annotation对它标注的元素被客户端使用时有影响时起作用
d, Inherited
该meta-annotation应用于目标为class的annotation类型上,被此annotattion标注的class会自动继承父类的annotation

4 、Annotation的反射
我们发现java.lang.Class有许多与Annotation的反射相关的方法,如getAnnotations、isAnnotationpresent
我们可以利用Annotation反射来做许多事情,比如自定义Annotation来做Model对象验证
代码
    @Retention(RetentionPolicy.RUNTIME)
   @Target({ ElementType.FIELD, ElementType.METHOD })
   public @interface RejectEmpty {
        /** hint title used in error message */
        String value() default "";
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target( { ElementType.FIELD, ElementType.METHOD })
   public @interface AcceptInt {
       int min() default Integer.MIN_VALUE;
       int max() default Integer.MAX_VALUE;
       String hint() default "";
   }
使用@RejectEmpty和@AcceptInt标注我们的Model的field,然后利用反射来做Model验证


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值