Java自定义注解之元注解

Java中元注解有四个: @Retention @Target @Documented @Inherited

1、@Retention

注解的保留位置

1
2
3
4
5
6
7
8
@Retention(RetentionPolicy.SOURCE)
//注解仅存在于源码中,在class字节码文件中不包含
 
@Retention(RetentionPolicy.CLASS)
// 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
 
@Retention(RetentionPolicy.RUNTIME)
// 注解会在class字节码文件中存在,在运行时可以通过反射获取到l

2、@Target

注解的作用目标。@Target 注解一般跟一个注解使用的目标位置,所有 Target 在注解 中指定

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */    TYPE,// 接口、类、枚举
 
    /** Field declaration (includes enum constants) */    FIELD,//字段、枚举的常量
 
    /** Method declaration */    METHOD,//方法
 
    /** Formal parameter declaration */    PARAMETER, //方法参数
 
    /** Constructor declaration */    CONSTRUCTOR, //构造函数
 
    /** Local variable declaration */    LOCAL_VARIABLE,//局部变量
 
    /** Annotation type declaration */    ANNOTATION_TYPE,//注解
     
    /** Package declaration */    PACKAGE,//包  
     
    /**
     * Type parameter declaration
     *
     * @since 1.8
     */    TYPE_PARAMETER, // 方法参数
    /**
     * Use of a type
     *
     * @since 1.8
     */    TYPE_USE
}

3、@Documented

说明该注解将被包含在javadoc中

4、@Inherited

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

发表评论

欢迎阅读『Java自定义注解之元注解|Java、开发语言、框架算法|Nick Tan-梓潼Blog』