Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。重点:和 Javadoc 不同,Java 标注可以通过反射获取标注内容。
在编译器生成类文件时,标注 可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容
- 内置注解
- @Override
- @Deprecated
- @SuppressWarnings
...
- 元注解 元注解就是给注解使用的注解
- @Retention 作用域-(常用)
表示在什么级别保存该注解信息。在实际开发中,我们一般都写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
}
* SOURCE:源代码时有用。
* CLASS:class文件中有用,但会被jvm丢弃。
* RUNTIME:运行时有用。
关系:RUNTIME>CLASS>SOURCE
后面我们自定义注解时,每个都需要用该注解!
- @Documented 作用文档 将此注解包含在 javadoc 中 ,它代表着此注解会被javadoc工具提取成文档。
无参的注解,作用域为RetentionPolicy.RUNTIME,运行时有用!这个只是用来作为标记,了解即可,在实际运行后会将该注解写入javadoc中,方便查看。
- @Target 目标-(常用) 标记这个注解应该是使用在哪种 Java 成员上面
![]()
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
}
注意这里是数组格式的参数,证明可以传多个值。
* @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)——包
- @Inherited 继承 标记这个注解是继承于哪个注解类(默认 注解并没有继承于任何子类)。
- 自定义注解
格式:修饰符(pulic)+ @interface +注解名+ {参数等}
可利用default 设置默认值,设定了默认值后使用注解时不传值也不会报错,反之报错!
自定义一个属于自己的注解
总结:注解主要配合反射来用



浙公网安备 33010602011771号