默認(rèn)情況下:sun編譯器以簡單的兩行的形式輸出警告。通過添加 -Xlint:keyWord 標(biāo)記(如:-Xlint:finally), 您可以獲得關(guān)鍵字keyword類型的完整說明。通過在關(guān)鍵字前添加破折號 -Xlint:-finally,您可以取消警告。
目前關(guān)鍵字清單:
all to suppress all warningsboxing to suppress warnings relative to boxing/unboxing Operationscast to suppress warnings relative to cast operationsdep-ann to suppress warnings relative to deprecated annotationdeprecation to suppress warnings relative to deprecationfallthrough to suppress warnings relative to missing breaks in switch statementsfinally to suppress warnings relative to finally block that don’t returnhiding to suppress warnings relative to locals that hide variableincomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)nls to suppress warnings relative to non-nls string literalsnull to suppress warnings relative to null analysisrawtypes to suppress warnings relative to un-specific types when using generics on class paramsrestriction to suppress warnings relative to usage of discouraged or forbidden referencesserial to suppress warnings relative to missing serialVersionUID field for a serializable classstatic-access
to suppress warnings relative to incorrect static accesssynthetic-access to suppress warnings relative to unoptimized access from inner classesunchecked to suppress warnings relative to unchecked operationsunqualified-field-access to suppress warnings relative to field access unqualifiedunused to suppress warnings relative to unused codedeprecation 使用了不贊成使用的類或方法時的警告 unchecked 執(zhí)行了未檢查的轉(zhuǎn)換時的警告,例如當(dāng)使用集合時沒有用泛型 (Generics) 來指定集合保存的類型。 fallthrough 當(dāng) Switch 程序塊直接通往下一種情況而沒有 Break 時的警告。 path 在類路徑、源文件路徑等中有不存在的路徑時的警告。 serial 當(dāng)在可序列化的類上缺少 serialVersionUID 定義時的警告。 finally 任何 finally 子句不能正常完成時的警告。 all 關(guān)于以上所有情況的警告
@SuppressWarnings 批注允許你選擇性的取消特點代碼段(類或方法)中的警告。是這樣想的:當(dāng)你看到警告時,你將調(diào)查它,如果你確定它不是問題,您就可以通過用@SuppressWarnings批注,以使你不會再看到警告。雖然聽起來似乎會屏蔽潛在的錯誤,但實際上它將提高代碼的安全性。(每一個警告都將值得注意)。
下面是使用 @SuppressWarnings 來取消 deprecation 警告的一個例子:
@SuppressWarnings 批注接受一個"value"變量,該變量是一個字符串?dāng)?shù)組,它指示將取消的警告。合法字符串的集合隨這編譯器的變化而變化,但在 JDK 上,可以傳遞給-Xlint 的是相同的關(guān)鍵字集合,并且要求編譯器忽略任何它們不能識別的關(guān)鍵字。
因為 @SuppressWarnings 批注僅接收一個參數(shù),并為該參數(shù)使用了特殊的名稱 "value",所以您可以選擇省略 value=,作為一種方便的縮寫:
public class DeprecatedUser2 {@SuppressWarnings({"deprecation"})public static void main(String[] args) {DeprecatedExample2.foo();}}您可以將單個數(shù)組參數(shù)中的任意數(shù)量的字符串值傳遞給批注,并在任何級別上放置批注。例如,以下示例代碼指示將取消整個類的 deprecation 警告,而僅在 main() 方法代碼內(nèi)取消 unchecked 和 fallthrough 警告:
import java.util.*;@SuppressWarnings({"deprecation"})public class NonGenerics {@SuppressWarnings({"unchecked","fallthrough"})public static void main(String[] args) {Runtime.runFinalizersOnExit();List list = new ArrayList();list.add("foo");}public static void foo() {List list = new ArrayList();list.add("foo");}}新聞熱點
疑難解答