作用:告訴編譯器忽略指定的警告,不用在編譯完成后出現警告信息。
使用:
@SuppressWarnings(“”)
@SuppressWarnings({})
@SuppressWarnings(value={})
示例:
-
@SuppressWarnings(“unchecked”)
告訴編譯器忽略 unchecked 警告信息,如使用List,ArrayList等未進行參數化產生的警告信息。
-
@SuppressWarnings(“serial”)
如果編譯器出現這樣的警告信息:The serializable class WmailCalendar does not declare a static final serialVersionUID field of type long
使用這個注釋將警告信息去掉。
-
@SuppressWarnings(“deprecation”)
如果使用了使用@Deprecated注釋的方法,編譯器將出現警告信息。
使用這個注釋將警告信息去掉。 -
@SuppressWarnings(“unchecked”, “deprecation”)
告訴編譯器同時忽略unchecked和deprecation的警告信息。
-
@SuppressWarnings(value={“unchecked”, “deprecation”})
等同於@SuppressWarnings(“unchecked”, “deprecation”)
1. 抑制單類型警告
@SuppressWarnings("unchecked") public void addItems(String item){ @SuppressWarnings("rawtypes") List items = new ArrayList(); items.add(item); }
- 1
- 2
- 3
- 4
- 5
- 6
2. 抑制多類型警告
@SuppressWarnings(value={"unchecked", "rawtypes"}) public void addItems(String item){ List items = new ArrayList(); items.add(item); }
- 1
- 2
- 3
- 4
- 5
3. 抑制全部警告
@SuppressWarnings("all") public void addItems(String item){ List items = new ArrayList(); items.add(item); }
- 1
- 2
- 3
- 4
- 5
注解目標
通過 @SuppressWarnings 的源碼可知,其注解目標為類、字段、函數、函數入參、構造函數和函數的局部變量。而家建議注解應聲明在最接近警告發生的位置。
抑制警告的關鍵字
allto suppress all warnings (抑制所有警告)boxingto suppress warnings relative to boxing/unboxing operations(抑制裝箱、拆箱操作時候的警告)castto suppress warnings relative to cast operations (抑制映射相關的警告)dep-annto suppress warnings relative to deprecated annotation(抑制啟用注釋的警告)deprecationto suppress warnings relative to deprecation(抑制過期方法警告)fallthroughto suppress warnings relative to missing breaks in switch statements(抑制確在switch中缺失breaks的警告)finallyto suppress warnings relative to finally block that don’t return (抑制finally模塊沒有返回的警告)hidingto suppress warnings relative to locals that hide variable()incomplete-switchto suppress warnings relative to missing entries in a switch statement (enum case)(忽略沒有完整的switch語句)nlsto suppress warnings relative to non-nls string literals(忽略非nls格式的字符)nullto suppress warnings relative to null analysis(忽略對null的操作)rawtypesto suppress warnings relative to un-specific types when using generics on class params(使用generics時忽略沒有指定相應的類型)restrictionto suppress warnings relative to usage of discouraged or forbidden referencesserialto suppress warnings relative to missing serialVersionUID field for a serializable class(忽略在serializable類中沒有聲明serialVersionUID變量)static-accessto suppress warnings relative to incorrect static access(抑制不正確的靜態訪問方式警告)synthetic-accessto suppress warnings relative to unoptimized access from inner classes(抑制子類沒有按最優方法訪問內部類的警告)uncheckedto suppress warnings relative to unchecked operations(抑制沒有進行類型檢查操作的警告)unqualified-field-accessto suppress warnings relative to field access unqualified (抑制沒有權限訪問的域的警告)unusedto suppress warnings relative to unused code (抑制沒被使用過的代碼的警告)- 參考:忽略警告注解@SuppressWarnings詳解
