注解的入門?
1、注解是針對Java編譯器的說明。
可以給Java包、類型(類、接口、枚舉)、構造器、方法、域、參數和局部變量進行注解。Java編譯器可以根據指令來解釋注解和放棄注解,或者將注解放到編譯后的生成的class文件中,運行時可用。
2、注解和注解類型
注解類型是一種特殊的接口類型,注解是注解注解類型的一個實例。
注解類型也有名稱和成員,注解中包含的信息采用鍵值對形式,可以有0個或多個。
3、Java中定義的一些注解:
@Override 告訴編譯器這個方法要覆蓋一個超類方法,防止程序員覆蓋出錯。
@Deprecated 這個標識方法或類(接口等類型)過期,警告用戶不建議使用。
@SafeVarargs JDK7新增,避免可變參數在使用泛型化時候警告”執行時期無法具體確認參數類型“,當然,也可以用@SuppressWarnings來避免檢查,顯然后者的抑制的范圍更大。
@SuppressWarnings(value={"unchecked"}) 抑制編譯警告,應用于類型、構造器、方法、域、參數以及局部變量。 value是類型數組,有效取值為:
all, to suppress all warnings
boxing, to suppress warnings relative to boxing/unboxing operations
cast, to suppress warnings relative to cast operations
dep-ann, to suppress warnings relative to deprecated annotation
deprecation, to suppress warnings relative to deprecation
fallthrough, to suppress warnings relative to missing breaks in switch statements
finally, to suppress warnings relative to finally block that don't return
hiding, to suppress warnings relative to locals that hide variable
incomplete-switch, to suppress warnings relative to missing entries in a switch statement (enum case)
javadoc, to suppress warnings relative to javadoc warnings
nls, to suppress warnings relative to non-nls string literals
null, to suppress warnings relative to null analysis
rawtypes, to suppress warnings relative to usage of raw types
restriction, to suppress warnings relative to usage of discouraged or forbidden references
serial, to suppress warnings relative to missing serialVersionUID field for a serializable class
static-access, to suppress warnings relative to incorrect static access
static-method, to suppress warnings relative to methods that could be declared as static
super, to suppress warnings relative to overriding a method without super invocations
synthetic-access, to suppress warnings relative to unoptimized access from inner classes
unchecked, to suppress warnings relative to unchecked operations
unqualified-field-access, to suppress warnings relative to field access unqualified
unused, to suppress warnings relative to unused code and dead code
4、注解的定義
使用 @interface 關鍵字聲明一個注解
public @interface MyAnnotation1
注解中可以定義屬性
String name default “defval”;
value是注解中的特殊屬性
注解中定義的屬性如果名稱為 value, 此屬性在使用時可以省寫屬性名
例如,聲明一個注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno1 {
String msg();
int value();
}