什么是注解
注解(annotation
)是一種形式化的方式把信息添加到代碼中,注解可以起到一種標記的作用,通過這個
標記可以進行對應(yīng)的邏輯處理,比如@override
則會在代碼編譯的時候檢查方法覆蓋。
元注解
負責創(chuàng)建新的注解,包括@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
}
可用參數(shù) | 說明 |
---|---|
TYPE |
類外傅、接口(包括注解類型) 或enum 聲明 |
FIELD |
成員變量 |
METHOD |
方法 |
PARAMETER |
參數(shù) |
CONSTRUCTOR |
構(gòu)造器 |
LOCAL_VARIABLE |
局部變量 |
ANNOTATION_TYPE |
注解類型 |
PACKAGE |
包 |
TYPE_PARAMETER |
范型參數(shù) |
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
}
可用參數(shù) | 說明 |
---|---|
SOURCE |
注解將被編譯器丟棄 |
CLASS |
注解在class 文件中可用, 但會被虛擬機丟棄 |
RUNTIME |
VM將運行期也保留注解信息,因此可用通過反射機制來讀取注解的信息 |
3. @Documented
,注解會包含在JavaDoc
中
4. @Inherited
表明該注解允許子類繼承父類中的注解.
有了注解俩檬,開發(fā)人員就可以做很多優(yōu)雅的事情萎胰,像Spring中的@Controller
如果想看注解的實踐,可以看另外一個文章 基于SpringBoot和注解實現(xiàn)優(yōu)雅的事件監(jiān)聽器