什么是注解
注解(annotation
)是一种形式化的方式把信息添加到代码中,注解可以起到一种标记的作用,通过这个
标记可以进行对应的逻辑处理,比如@override
则会在代码编译的时候检查方法覆盖。
元注解
负责创建新的注解,包括@Target
,@Retention
,@Documented
,@Inherited
。
1. @Target
,表示该注解可以用于什么地方。
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
}
可用参数 | 说明 |
---|---|
TYPE |
类、接口(包括注解类型) 或enum 声明 |
FIELD |
成员变量 |
METHOD |
方法 |
PARAMETER |
参数 |
CONSTRUCTOR |
构造器 |
LOCAL_VARIABLE |
局部变量 |
ANNOTATION_TYPE |
注解类型 |
PACKAGE |
包 |
TYPE_PARAMETER |
范型参数 |
2. @Retention
: 表示该注解信息保存到什么级别
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 文件中可用, 但会被虚拟机丢弃 |
RUNTIME |
VM将运行期也保留注解信息,因此可用通过反射机制来读取注解的信息 |
3. @Documented
,注解会包含在JavaDoc
中
4. @Inherited
表明该注解允许子类继承父类中的注解.
有了注解,开发人员就可以做很多优雅的事情,像Spring中的@Controller
如果想看注解的实践,可以看另外一个文章 基于SpringBoot和注解实现优雅的事件监听器
网友评论