java元注解_Java 元注解

学习Android APT需要我们具备自定义注解以及注解处理器的相关知识,这里简单介绍下Java元注解。注解是在JDK1.5后引入的,包含了4种元注解:@Target @Retention @Documented @Inherited

1. @Target

用于声明注解的作用位置,即使用对象。在下面的 ElementType 枚举中我们可以清楚看到 @Target 所能接受的值以及对应的使用范围。其中需要注意的是TYPE_PARAMETER和TYPE_USE是在JDK 1.8后引入的。

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

}

2. @Retention

用于声明注解的保留范围,相当于作用域,即在什么时候可以使用。

SOURCE表示该注解只能保留在源代码中,在编译时会被丢弃,不会在class字节码文件中出现

CLASS表示该注解可以保留在class字节码文件中,即编译时可用

RUNTIME表示该注解可在代码运行时保留,可以通过反射获得

public enum RetentionPolicy {

/**

* Annotations are to be discarded by the compiler.

*/

SOURCE,

/**

* 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

}

3. @Documented

表示拥有该注解的元素可以被 javadoc 这类的工具文档化。

4.@Inherited

表示允许子类继承父类中的注解。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值