篇五:自定义注解

一、创建interface类

//创建interface类,在interface前添加@
public @interface DataSource {

}

 

二、元注解(配置项)说明

@Retention :定义注解的保留策

@Target :定义注解的作用目标

@Document :该注解将被包含在javadoc中

@Inherited :说明子类可以继承父类中的该注解

 

三、@Retention

  有三种选择项,常选择 RetentionPolicy.RUNTIME

  @Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
  @Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
  @Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
 
 
四、@Target 
  有8种选项值,常用ElementType.METHOD、ElementType.TYPE
  @Target(ElementType.TYPE)   //接口、类、枚举、注解
  @Target(ElementType.FIELD) //字段、枚举的常量
  @Target(ElementType.METHOD) //方法
  @Target(ElementType.PARAMETER) //方法参数
  @Target(ElementType.CONSTRUCTOR)  //构造函数
  @Target(ElementType.LOCAL_VARIABLE)//局部变量
  @Target(ElementType.ANNOTATION_TYPE)//注解
  @Target(ElementType.PACKAGE) ///包   
 
五、例子
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
    String value();
}

 

  
posted @ 2017-01-05 17:29  刘广平  阅读(203)  评论(0)    收藏  举报