一绞旅、概念
Annontation是Java5開始引入的新特征。中文名稱一般叫注解。它提供了一種安全的類似注釋的機(jī)制,用來將任何的信息或元數(shù)據(jù)(metadata)與程序元素(類把夸、方法、成員變量等)進(jìn)行關(guān)聯(lián)铭污。
更通俗的意思是為程序的元素(類恋日、方法、成員變量)加上更直觀更明了的說明嘹狞,這些說明信息是與程序的業(yè)務(wù)邏輯無關(guān)岂膳,并且是供指定的工具或框架使用的。
Annontation像一種修飾符一樣磅网,應(yīng)用于包谈截、類型、構(gòu)造方法、方法傻盟、成員變量速蕊、參數(shù)及本地變量的聲明語句中。
這邊只了解一下 Retention 與 Target
二 娘赴、使用
@Retention(保留)
告知編譯程序如何處理
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
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.
* 編譯程序處理完注解信息后存儲(chǔ)在class中规哲,缺省
*/
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.
* 編譯程序處理完注解信息后存儲(chǔ)在class中,可由VM讀入
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
SOURCE 例子:
SuppressWarning 作用是在編譯時(shí)抑制警告诽表,不必寫入到class中
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {...}
CLASS 例子:
butterknife 框架
編譯時(shí)將注解寫入class文件中唉锌。
---- RUNTIME 例子:
@Target(元元素)
表示注釋類型的程序元素的種類
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
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
* @hide 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
* @hide 1.8
*/
TYPE_USE
}