码迷,mamicode.com
首页 > 其他好文 > 详细

自定义注解

时间:2018-07-23 19:11:52      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:run   com   参数   document   package   ref   bsp   ota   def   

  在开始学习自定义注解之前,我们需要了解下一个注解的基本构成。这就要说到 java.lang.annotation提供的四种元注解了,分别是@Documented、@Target、@Retention和@Inherited。接下来我们就来好好地说道说道,这几个注解是如何组合来完成注解的自定义的。

  @Documented:这是个比较简单的注解,它的功能就是表示是否要将注解信息添加到Java文档中。

  @Inherited:这是一个标记注解,如果自定义的注解被@Inherited修饰,那么该注解修饰类的子类就会自动的继承这个注解,反之则不会自动的继承。

  @Target:@Target主要是指定该自定义注解作用于何处。它有一个ElementType的参数,常见定义如下:

  public enum ElementType {
   /** Class, interface (including annotation type), or enum declaration */
   TYPE,//(用于)类、接口(包含注解类型)或enum声明
   /** Field declaration (includes enum constants) */
   FIELD,//成员变量、对象或属性(包含enum变量)
   /** Method declaration */
   METHOD,//用于方法(常用)
   /** Formal parameter declaration */
   PARAMETER,//用于参数
   /** Constructor declaration */
   CONSTRUCTOR,//用于构造器
   /** Local variable declaration */
   LOCAL_VARIABLE,//用于局部变量
   /** Package declaration */
   PACKAGE//用于包
  }
@Retention:
用于表示注解的生命周期。参数RetentionPolicy如下定义:
  public enum RetentionPolicy {
   /**
   * Annotations are to be discarded by the compiler.
   */
   SOURCE,//编译阶段会被丢弃,并且不会写入字节码(如@Override, @SuppressWarnings等)
   /**
  * Annotations are to be recorded in the class file by the compiler
   * but need not be retained by the VM at run time. This is the default
   * behavior.
   */
   CLASS,//类加载的时候丢弃,默认使用该属性
   /**
   * Annotations are to be recorded in the class file by the compiler and
   * retained by the VM at run time, so they may be read reflectively.
   *
   * @see java.lang.reflect.AnnotatedElement
   */
   RUNTIME//始终不会被丢弃(最常用)
}
 未完。。。

 

自定义注解

标签:run   com   参数   document   package   ref   bsp   ota   def   

原文地址:https://www.cnblogs.com/ymx8573/p/9356298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!