Java注解的一些说明

  1. public enum RetentionPolicy {
  2.     /**
  3.      * Annotations are to be discarded by the compiler.
  4.      */
  5.     SOURCE,
  6.     /**
  7.      * Annotations are to be recorded in the class file by the compiler
  8.      * but need not be retained by the VM at run time.  This is the default
  9.      * behavior.
  10.      */
  11.     CLASS,
  12.     /**
  13.      * Annotations are to be recorded in the class file by the compiler and
  14.      * retained by the VM at run time, so they may be read reflectively.
  15.      *
  16.      * @see java.lang.reflect.AnnotatedElement
  17.      */
  18.     RUNTIME
  19. }

这是一个enum类型,共有三个值,分别是SOURCE,CLASS 和 RUNTIME.
   SOURCE代表的是这个Annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,Annotation的数据就会消失,并不会保留在编译好的.class文件里面。
   ClASS的意思是这个Annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这一些信息加载到虚拟机(JVM)中去.注意一下,当你没有设定一个Annotation类型的Retention值时,系统默认值是CLASS.
   第三个,是RUNTIME,表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的.

 

  1. public enum ElementType {
  2.     /** Class, interface (including annotation type), or enum declaration */
  3.     TYPE,
  4.     /** Field declaration (includes enum constants) */
  5.     FIELD,
  6.     /** Method declaration */
  7.     METHOD,
  8.     /** Parameter declaration */
  9.     PARAMETER,
  10.     /** Constructor declaration */
  11.     CONSTRUCTOR,
  12.     /** Local variable declaration */
  13.     LOCAL_VARIABLE,
  14.     /** Annotation type declaration */
  15.     ANNOTATION_TYPE,
  16.     /** Package declaration */
  17.     PACKAGE
  18. }
@Target里面的ElementType是用来指定Annotation类型可以用在哪一些元素上的.说明一下:TYPE(类型), FIELD(属性), METHOD(方法), PARAMETER(参数), CONSTRUCTOR(构造函数),LOCAL_VARIABLE(局部变量), ANNOTATION_TYPE,PACKAGE(包),其中的TYPE(类型)是指可以用在Class,Interface,Enum和Annotation类型上.
   另外,从1的源代码可以看出,@Target自己也用了自己来声明自己,只能用在ANNOTATION_TYPE之上.
   如果一个Annotation类型没有指明@Target使用在哪些元素上,那么它可以使用在任何元素之上,这里的元素指的是上面的八种类型.

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值