背景:
J2SE提供的最后一個注解是@SuppressWarnings。該批注的作用是給編譯器一條指令,告訴它對被批注的代碼元素內部的某些警告保持靜默。
@SuppressWarnings注解允許您選擇性地取消特定代碼段(即,類或方法)中的警告。其中的想法是當您看到警告時,您將調查它,如果您確定它不是問題,您就可以添加一個@SuppressWarnings注解,以使您不會再看到警告。雖然它聽起來似乎會屏蔽潛在的錯誤,但實際上它將提高代碼安全性,因為它將防止您對警告無動於衷 — 您看到的每一個警告都將值得注意。
一、@SuppressWarings注解
作用:用於抑制編譯器產生警告信息。
示例1、抑制單類型的警告:
@SuppressWarnings("unchecked") public void addItems(String item){ @SuppressWarnings("rawtypes") List items = new ArrayList(); items.add(item); }
示例2、抑制多類型的警告:
@SuppressWarnings(value={"unchecked", "rawtypes"}) public void addItems(String item){ List items = new ArrayList(); items.add(item); }
示例3、抑制所有類型的警告:
@SuppressWarnings("all") public void addItems(String item){ List items = new ArrayList(); items.add(item); }
二、注解目標
通過@SuppressWarnings的源碼可知,其注解目標為類、字段、函數、函數入參、構造函數和函數的局部變量。
而大家建議注解應聲明在最接近警告發生的位置。
二、抑制警告的關鍵字
- 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(抑制確在switch中缺失breaks的警告)
- finally to suppress warnings relative to finally block that don’t return (抑制finally模塊沒有返回的警告)
- 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)(忽略沒有完整的switch語句)
- nls to suppress warnings relative to non-nls string literals(忽略非nls格式的字符)
- null to suppress warnings relative to null analysis(忽略對null的操作)
- rawtypes to suppress warnings relative to un-specific types when using generics on class params(使用generics時忽略沒有指定相應的類型)
- 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(忽略在serializable類中沒有聲明serialVersionUID變量)
- 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 (抑制沒被使用過的代碼的警告)
參考:
http://blog.csdn.net/sysware_carol/article/details/52100580(以上內容轉自此篇文章)