古詩詞大全網 - 古詩大全 - Java 什麽是註解及註解原理詳細介紹

Java 什麽是註解及註解原理詳細介紹

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();

}