天天看點

Java注解@SuppressWarnings

概述

作用:用于抑制編譯器産生警告資訊,即IDEA裡面的黃色代碼塊。

抑制單類型的警告:

@SuppressWarnings("unchecked")
public void add(String item) {
   List items = new ArrayList();
   items.add(item);
}      

抑制多類型的警告:

@SuppressWarnings(value={"unchecked", "rawtypes"})
public void add(String item) {
   List items = new ArrayList();
   items.add(item);
}      

抑制所有類型的警告:

@SuppressWarnings("all")      

通過 @SuppressWarnings 的源碼可知,其注解目标為類、字段、函數、函數入參、構造函數和函數的局部變量。建議注解應聲明在最接近警告發生的位置。

抑制警告的關鍵字

關鍵字 用途
all to suppress all warnings
boxing to suppress warnings relative to boxing/unboxing operations
UnstableApiUsage to suppress warnings x-is-marked-unstable
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)
nls to suppress warnings relative to non-nls string literals
null to suppress warnings relative to null analysis
rawtypes to suppress warnings relative to un-specific types when using generics on class params
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
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

Java Lint選項

  1. lint的含義

    用于在編譯程式的過程中,進行更細節的額外檢查。

  2. javac 的标準選項和非标準選項

    标準選項:是指目前版本和未來版本中都支援的選項,如 -cp 和 -d 等。

    非标準選項:是指目前版本支援,但未來不一定支援的選項。通過 javac -X 檢視目前版本支援的非标準選項。

  3. 檢視警告資訊

    預設情況下執行 javac 僅僅顯示警告的扼要資訊,也不過阻止編譯過程。若想檢視警告的詳細資訊,則需要執行​​

    ​javac -Xlint:keyword​

    ​來編譯源碼。

總結

  1. 對于泛型,一定要指定泛型類型。而不是使用raw type,即Object類型,​

    ​List a = new ArrayList();​

    ​,再加上SuppressWarnings注解。因為假如後面如果想要從List裡面取元素出來,可能出現錯誤的将String元素轉型為Integer,造成classCastException,或者NumberFormatException;
  2. 對于無用的方法或者類,立馬删除,而不是加​

    ​@SuppressWarnings("unused")​

    ​,髒代碼會破壞閱讀體驗;

參考