1. 程式人生 > >FindBugs規則整理

FindBugs規則整理

FindBugs是基於Bug Patterns概念,查詢javabytecode(.class檔案)中的潛在bug,主要檢查bytecode中的bug patterns,如NullPoint空指標檢查、沒有合理關閉資源、字串相同判斷錯(==,而不是equals)等

一、Security 關於程式碼安全性防護
1.Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD)
程式碼中建立DB的密碼時採用了寫死的密碼。
2.Dm: Empty database password (DMI_EMPTY_DB_PASSWORD)
建立資料庫連線時沒有為資料庫設定密碼,這會使資料庫沒有必要的保護。
3.HRS: HTTP cookie formed from untrusted input (HRS_REQUEST_PARAMETER_TO_COOKIE)
此程式碼使用不受信任的HTTP引數構造一個HTTP Cookie。
4.HRS: HTTP Response splitting vulnerability (HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)
在程式碼中直接把一個HTTP的引數寫入一個HTTP標頭檔案中,它為HTTP的響應暴露了漏洞。
5.SQL: Nonconstant string passed to execute method on an SQL statement (SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)
該方法以字串的形式來呼叫SQLstatement的execute方法,它似乎是動態生成SQL語句的方法。這會更容易受到SQL注入攻擊。
6.XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)
在程式碼中在JSP輸出中直接寫入一個HTTP引數,這會造成一個跨站點的指令碼漏洞。
二、Experimental
1.LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)
OpenJDK的引入了一種潛在的不相容問題,特別是,java.util.logging.Logger的行為改變時。它現在使用內部弱引用,而不是強引用。–logger配置改變,它就是丟失對logger的引用,這本是一個合理的變化,但不幸的是一些程式碼對舊的行為有依賴關係。這意味著,當進行垃圾收集時對logger配置將會丟失。例如:
public static void initLogging() throws Exception {
 Logger logger = Logger.getLogger("edu.umd.cs");
 logger.addHandler(new FileHandler()); // call to change logger configuration
 logger.setUseParentHandlers(false); // another call to change logger configuration
}
該方法結束時logger的引用就丟失了,如果你剛剛結束呼叫initLogging方法後進行垃圾回收,logger的配置將會丟失(因為只有保持記錄器弱引用)。
public static void main(String[] args) throws Exception {
 initLogging(); // adds a file handler to the logger
 System.gc(); // logger configuration lost
 Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
}
2.OBL: Method may fail to clean up stream or resource (OBL_UNSATISFIED_OBLIGATION)
這種方法可能無法清除(關閉,處置)一個流,資料庫物件,或其他資源需要一個明確的清理行動。
一般來說,如果一個方法開啟一個流或其他資源,該方法應該使用try / finally塊來確保在方法返回之前流或資源已經被清除了。這種錯誤模式基本上和OS_OPEN_STREAM和ODR_OPEN_DATABASE_RESOURCE錯誤模式相同,但是是在不同在靜態分析技術。我們正為這個錯誤模式的效用收集反饋意見。

三、Bad practice程式碼實現中的一些壞習慣
1.AM: Creates an empty jar file entry (AM_CREATES_EMPTY_JAR_FILE_ENTRY)
呼叫putNextEntry()方法寫入新的 jar 檔案條目時立即呼叫closeEntry()方法。這樣會造成JarFile條目為空。
2.AM: Creates an empty zip file entry (AM_CREATES_EMPTY_ZIP_FILE_ENTRY)
呼叫putNextEntry()方法寫入新的 zip 檔案條目時立即呼叫closeEntry()方法。這樣會造成ZipFile條目為空。
3.BC: Equals method should not assume anything about the type of its argument (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)
equals(Object o)方法不能對引數o的型別做任何的假設。比較此物件與指定的物件。當且僅當該引數不為 null,並且是表示與此物件相同的型別的物件時,結果才為 true。
4.BC: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)
隨機建立物件只使用過一次就拋棄
5.BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK)
檢查位操作符執行是否合理
((event.detail & SWT.SELECTED) > 0)
If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '> 0'.
6.CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)
按照慣例,實現此介面的類應該使用公共方法重寫 Object.clone(它是受保護的),以獲得有關重寫此方法的詳細資訊。此介面不 包含 clone 方法。因此,因為某個物件實現了此介面就克隆它是不可能的,應該實現此介面的類應該使用公共方法重寫 Object.clone
7.CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL)
一個非final型別的類定義了clone()方法而沒有呼叫super.clone()方法。例如:B擴充套件自A,如果B中clone方法呼叫了spuer.clone(),而A中的clone沒有呼叫spuer.clone(),就會造成結果型別不準確。要求A的clone方法中呼叫spuer.clone()方法。
8.CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)
類中定義了clone方法但是它沒有實現Cloneable介面
9.Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)
抽象類中定義了多個compareTo()方法,正確的是覆寫Comparable中的compareTo方法,方法的引數為Object型別,如下例:
int compareTo(T o)  比較此物件與指定物件的順序。
10.Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)
類中定義了多個compareTo()方法,正確的是覆寫Comparable中的compareTo方法,方法的引數為Object型別
11.DE: Method might drop exception (DE_MIGHT_DROP)
方法可能丟擲異常
12.DE: Method might ignore exception (DE_MIGHT_IGNORE)
方法可能忽略異常
13.DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)
不要用removeAll方法去clear一個集合
14.DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)
類載入器只能建立在特殊的方法體內
15.Dm: Method invokes System.exit(...) (DM_EXIT)
在方法中呼叫System.exit(...)語句,考慮用RuntimeException來代替
16.Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)
在方法中呼叫了System.runFinalizersOnExit 或者Runtime.runFinalizersOnExit方法,因為這樣做是很危險的。
17.ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)
用==或者!=方法去比較String型別的引數
18.ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)
用==或者!=去比較String型別的物件
19.Eq: Abstract class defines covariant equals() method (EQ_ABSTRACT_SELF)
20.Eq: Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)
equals方法檢查不一致的操作。兩個類根本就是父子關係而去呼叫equals方法去判讀物件是否相等。
public boolean equals(Object o) {
  if (o instanceof Foo)
    return name.equals(((Foo)o).name);
  else if (o instanceof String)
    return name.equals(o);
  else return false;
21.Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)
類中定義了compareTo方法但是繼承了Object中的compareTo方法
22.Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)
類中的equals方法可能被子類中的方法所破壞,當使用類似於Foo.class == o.getClass()的判斷時考慮用this.getClass() == o.getClass()來替換
23.Eq: Covariant equals() method defined (EQ_SELF_NO_OBJECT)
類中定義了多個equals方法。正確的做法是覆寫Object中的equals方法,它的引數為Object型別的物件。
24.FI: Empty finalizer should be deleted (FI_EMPTY)
為空的finalizer方法應該刪除。一下關於finalizer的內容省略
25.GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)
This call to a generic collection method passes an argument while compile type Object where a specific type from the generic type parameters is expected. Thus, neither the standard Java type system nor static analysis can provide useful information on whether the object being passed as a parameter is of an appropriate type.
26.HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)
方法定義了equals方法卻沒有定義hashCode方法
27.HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)
 類定義了hashCode方法去沒有定義equal方法
28.HE: Class defines equals() and uses Object.hashCode() (HE_EQUALS_USE_HASHCODE)
一個類覆寫了equals方法,沒有覆寫hashCode方法,使用了Object物件的hashCode方法
29.HE: Class inherits equals() and uses Object.hashCode() (HE_INHERITS_EQUALS_USE_HASHCODE)
子類繼承了父類的equals方法卻使用了Object的hashCode方法
30.IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)
子類在父類未初始化之前使用父類物件例項
public class CircularClassInitialization {
	static class InnerClassSingleton extends CircularClassInitialization {
static InnerClassSingleton singleton = new InnerClassSingleton();
	}	
	static CircularClassInitialization foo = InnerClassSingleton.singleton;
}
31.IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)
捕捉違法的監控狀態異常,例如當沒有獲取到物件鎖時使用其wait和notify方法
32.ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)
為使用靜態方法而建立一個例項物件。呼叫靜態方法時只需要使用類名+靜態方法名就可以了。
33.It: Iterator next() method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT)
迭代器的next方法不能夠丟擲NoSuchElementException
34.J2EE: Store of non serializable object into HttpSession (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)
在HttpSession物件中儲存非連續的物件
35.JCIP: Fields of immutable classes should be final (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)
 The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require that all fields are final. .
36.NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL)
返回值為boolean型別的方法直接返回null,這樣會導致空指標異常
37.NP: equals() method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)
變數呼叫equals方法時沒有進行是否為null的判斷
38.NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL)
toString方法可能返回null
39.Nm: Class names should start with an upper case letter (NM_CLASS_NAMING_CONVENTION)
類的名稱以大寫字母名稱開頭
40.Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION)
類的名稱中含有Exception但是卻不是一個異常類的子類,這種名稱會造成混淆
41.Nm: Confusing method names (NM_CONFUSING)
令人迷惑的方面命名
42.Nm: Field names should start with a lower case letter (NM_FIELD_NAMING_CONVENTION)
非final型別的欄位需要遵循駝峰命名原則
43.Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)
驗證是否是java預留關鍵字
44.Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)
驗證是否時java中的關鍵字
45.Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION)
方法名稱以小寫字母開頭
46.Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE)
實現同一介面實現類不能使用相同的名稱,即使它們位於不同的包中
47.Nm: Class names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)
繼承同一父類的子類不能使用相同的名稱,即使它們位於不同的包中
48.Nm: Very confusing method names (but perhaps intentional) (NM_VERY_CONFUSING_INTENTIONAL)
很容易混淆的方法命名,例如方法的名稱名稱使用使用大小寫來區別兩個不同的方法。
49.Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL)
由於錯誤引用了不同包中相同類名的物件而不能夠正確的覆寫父類中的方法
import alpha.Foo;
public class A {
  public int f(Foo x) { return 17; }
}
import beta.Foo;
public class B extends A {
  public int f(Foo x) { return 42; }
  public int f(alpha.Foo x) { return 27; }
}
50.ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE)
方法中可能存在關閉資料連線失敗的情況
51.OS: Method may fail to close stream (OS_OPEN_STREAM)
方法中可能存在關閉流失敗的情況
52.OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)
方法中可能存在關閉流時出現異常情況
53.RC: Suspicious reference comparison to constant (RC_REF_COMPARISON_BAD_PRACTICE)
當兩者為不同型別的物件時使用equals方法來比較它們的值是否相等,而不是使用==方法。例如比較的兩者為java.lang.Integer, java.lang.Float
54.RC: Suspicious reference comparison of Boolean values (RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN)
使用== 或者 !=操作符來比較兩個 Boolean型別的物件,建議使用equals方法。
55.RR: Method ignores results of InputStream.read() (RR_NOT_CHECKED)
InputStream.read方法忽略返回的多個字元,如果對結果沒有檢查就沒法正確處理使用者讀取少量字元請求的情況。
56.RR: Method ignores results of InputStream.skip() (SR_NOT_CHECKED)
InputStream.skip()方法忽略返回的多個字元,如果對結果沒有檢查就沒法正確處理使用者跳過少量字元請求的情況
57.RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)
方法忽略返回值的異常資訊
58.SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)
在所有的static final欄位賦值之前去使用靜態初始化的方法建立一個類的例項。
59.Se: Non-serializable value stored into instance field of a serializable class (SE_BAD_FIELD_STORE)
非序列化的值儲存在宣告為序列化的的非序列化欄位中
60.Se: Comparator doesn't implement Serializable (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)
Comparator介面沒有實現Serializable介面
61.Se: Serializable inner class (SE_INNER_CLASS)
序列化內部類
62.Se: serialVersionUID isn't final (SE_NONFINAL_SERIALVERSIONID)
關於UID類的檢查內容省略
63.Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR)
子類序列化時父類沒有提供一個void的建構函式
64.Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)
Externalizable 例項類沒有定義一個void型別的建構函式
65.Se: The readResolve method must be declared with a return type of Object. (SE_READ_RESOLVE_MUST_RETURN_OBJECT)
readResolve從流中讀取類的一個例項,此方法必須宣告返回一個Object型別的物件
66.Se: Transient field that isn't set by deserialization. (SE_TRANSIENT_FIELD_NOT_RESTORED)
This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deserialized instance of the class.
67.SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID)
一個類實現了Serializable介面但是沒有定義serialVersionUID型別的變數。序列化執行時使用一個稱為 serialVersionUID 的版本號與每個可序列化類相關聯,該序列號在反序列化過程中用於驗證序列化物件的傳送者和接收者是否為該物件載入了與序列化相容的類。如果接收者載入的該物件的類的 serialVersionUID 與對應的傳送者的類的版本號不同,則反序列化將會導致 InvalidClassException。可序列化類可以通過宣告名為 "serialVersionUID" 的欄位(該欄位必須是靜態 (static)、最終 (final) 的 long 型欄位)顯式宣告其自己的 serialVersionUID: 
 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
68.UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)
當一個類被子類繼承後不要使用this.getClass().getResource(...)來獲取資源
四、Correctness關於程式碼正確性相關方面的
1.BC: Impossible cast (BC_IMPOSSIBLE_CAST)
不可能的類轉換,執行時會丟擲ClassCastException
2.BC: Impossible downcast (BC_IMPOSSIBLE_DOWNCAST)
父類在向下進行型別轉換時丟擲ClassCastException
3.BC: Impossible downcast of toArray() result (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)
集合轉換為陣列元素時發生的類轉換錯誤。
This code is casting the result of calling toArray() on a collection to a type more specific than Object[], as in: 
String[] getAsArray(Collection<String> c) {
  return (String[]) c.toArray();
  }
This will usually fail by throwing a ClassCastException. The toArray() of almost all collections return an Object[]. They can't really do anything else, since the Collection object has no reference to the declared generic type of the collection. 
The correct way to do get an array of a specific type from a collection is to use c.toArray(new String[]); or c.toArray(new String[c.size()]); (the latter is slightly more efficient). 
4.BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF)
採用instaneof方法進行比較時總是返回false。前提是保證它不是由於某些邏輯錯誤造成的。
5.BIT: Incompatible bit masks (BIT_AND)
錯誤的使用&位操作符,例如(e & C)
6.BIT: Check to see if ((...) & 0) == 0 (BIT_AND_ZZ)
檢查恆等的邏輯錯誤
7.BIT: Incompatible bit masks (BIT_IOR)
錯誤的使用|位操作符,例如(e | C)
8.BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT)
檢查邏輯運算子操作返回的標識。例如((event.detail & SWT.SELECTED) > 0),建議採用!=0代替>0
9.BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER)
子類錯誤的覆寫父類中用於適配監聽其他事件的方法,從而導致當觸發條件發生時不能被監聽者呼叫
10.Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)
在三元運算子操作時如果沒有對值進行封裝或者型別轉換。例如:b ? e1 : e2
11.DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL)
以類的字面名稱方式為一個欄位賦值後再也沒有去使用它,在1.4jdk中它會自動呼叫靜態的初始化方法,而在jdk1.5中卻不會去執行。
12.DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT)
覆寫增量增加錯誤i = i++
13.DMI: Bad constant value for month (DMI_BAD_MONTH)
hashNext方法呼叫next方法。
14.DMI: Collections should not contain themselves (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)
集合沒有包含他們自己本身。
15.DMI: Invocation of hashCode on an array (DMI_INVOKING_HASHCODE_ON_ARRAY)
陣列直接使用hashCode方法來返回雜湊碼。
int [] a1 = new int[]{1,2,3,4};
System.out.println(a1.hashCode());
System.out.println(java.util.Arrays.hashCode(a1));
16.DMI: Double.longBitsToDouble invoked on an int (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)
17.DMI: Vacuous call to collections (DMI_VACUOUS_SELF_COLLECTION_CALL)
集合的呼叫不能被感知。例如c.containsAll(c)總是返回true,而c.retainAll(c)的返回值不能被感知。
18.Dm: Can't use reflection to check for presence of annotation without runtime retention (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)
Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection (e.g., by using the isAnnotationPresent method). .
19.Dm: Useless/vacuous call to EasyMock method (DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD)
While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect.
20.EC: equals() used to compare array and nonarray (EC_ARRAY_AND_NONARRAY)
陣列物件使用equals方法和非陣列物件進行比較。即使比較的雙方都是陣列物件也不應該使用equals方法,而應該比較它們的內容是否相等使用java.util.Arrays.equals(Object[], Object[]);
21.EC: equals(...) used to compare incompatible arrays (EC_INCOMPATIBLE_ARRAY_COMPARE)
使用equls方法去比較型別不相同的陣列。例如:String[] and StringBuffer[], or String[] and int[]
22.EC: Call to equals() with null argument (EC_NULL_ARG)
呼叫equals的物件為null
23.EC: Call to equals() comparing unrelated class and interface (EC_UNRELATED_CLASS_AND_INTERFACE)
使用equals方法比較不相關的類和介面
24.EC: Call to equals() comparing different interface types (EC_UNRELATED_INTERFACES)
呼叫equals方法比較不同型別的介面
25.EC: Call to equals() comparing different types (EC_UNRELATED_TYPES)
呼叫equals方法比較不同型別的類
26.EC: Using pointer equality to compare different types (EC_UNRELATED_TYPES_USING_POINTER_EQUALITY)
This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime.
27.Eq: equals method always returns false (EQ_ALWAYS_FALSE)
使用equals方法返回值總是false
28.Eq: equals method always returns true (EQ_ALWAYS_TRUE)
equals方法返回值總是true
29.Eq: equals method compares class names rather than class objects (EQ_COMPARING_CLASS_NAMES)
使用equals方法去比較一個類的例項和類的型別
30.Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)
This class defines an enumeration, and equality on enumerations are defined using object identity. Defining a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don't do it.
31.Eq: equals() method defined that doesn't override equals(Object) (EQ_OTHER_NO_OBJECT)
類中定義的equals方法時不要覆寫equals(Object)方法
32.Eq: equals() method defined that doesn't override Object.equals(Object) (EQ_OTHER_USE_OBJECT)
類中定義的equals方法時不要覆寫Object中的equals(Object)方法
33.Eq: equals method overrides equals in superclass and may not be symmetric (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)
34.Eq: Covariant equals() method defined, Object.equals(Object) inherited (EQ_SELF_USE_OBJECT)
類中定義了一組equals方法,但是都是繼承的java.lang.Object class中的equals(Object)方法
35.FE: Doomed test for equality to NaN (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)
This code checks to see if a floating point value is equal to the special Not A Number value (e.g., if (x == Double.NaN)). However, because of the special semantics of NaN, no value is equal to Nan, including NaN. Thus, x == Double.NaN always evaluates to false. To check to see if a value contained in x is the special Not A Number value, use Double.isNaN(x) (or Float.isNaN(x) if x is floating point precision).
36.FS: Format string placeholder incompatible with passed argument (VA_FORMAT_STRING_BAD_ARGUMENT)
錯誤使用引數型別來格式化字串
37.FS: The type of a supplied argument doesn't match format specifier (VA_FORMAT_STRING_BAD_CONVERSION)
指定的格式字串和引數型別不匹配,例如:String.format("%d", "1")
38.FS: MessageFormat supplied where printf style format expected (VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED)
但用String的format方法時實際呼叫了MessageFormat中乾的格式化方法而引起格式化結果出錯。
39.FS: More arguments are passed than are actually used in the format string (VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED)
使用String的format方法時有非法的引數也經過了格式化操作。
40.FS: Illegal format string (VA_FORMAT_STRING_ILLEGAL)
格式化String物件語句錯誤
41.FS: Format string references missing argument (VA_FORMAT_STRING_MISSING_ARGUMENT)
String的format操作缺少必要的引數。
42.FS: No previous argument for format string (VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT)
格式字串定義錯誤,例如:formatter.format("%<s %s", "a", "b"); 丟擲MissingFormatArgumentException異常
43.GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)
This call to a generic collection method contains an argument with an incompatible class from that of the collection's parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is being passed to the method.
In general, instances of two unrelated classes are not equal. For example, if the Foo and Bar classes are not related by subtyping, then an instance of Foo should not be equal to an instance of Bar. Among other issues, doing so will likely result in an equals method that is not symmetrical. For example, if you define the Foo class so that a Foo can be equal to a String, your equals method isn't symmetrical since a String can only be equal to a String. 
In rare cases, people do define nonsymmetrical equals methods and still manage to make their code work. Although none of the APIs document or guarantee it, it is typically the case that if you check if a Collection<String> contains a Foo, the equals method of argument (e.g., the equals method of the Foo class) used to perform the equality checks. 
44.HE: Signature declares use of unhashable class in hashed construct (HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS)
A method, field or class declares a generic signature where a non-hashable class is used in context where a hashable class is required. A class that declares an equals method but inherits a hashCode() method from Object is unhashable, since it doesn't fulfill the requirement that equal objects have equal hashCodes.
45.HE: Use of class without a hashCode() method in a hashed data structure (HE_USE_OF_UNHASHABLE_CLASS)
A class defines an equals(Object) method but not a hashCode() method, and thus doesn't fulfill the requirement that equal objects have equal hashCodes. An instance of this class is used in a hash data structure, making the need to fix this problem of highest importance.
46.ICAST: integral value cast to double and then passed to Math.ceil (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)
integral的值轉換為double後使用了Math.ceil方法
47.ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)
int 型別的值轉換為float型別之後呼叫了Math.round方法
48.IJU: JUnit assertion in run method will not be noticed by JUnit (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)
在JUnit中的斷言在run方法中不會被告知
49.IJU: TestCase declares a bad suite method (IJU_BAD_SUITE_METHOD)
在一個JUnit類中宣告的一個suite()方法必須宣告為
public static junit.framework.Test suite()
或者
public static junit.framework.TestSuite suite()的形式。
50.IL: A collection is added to itself (IL_CONTAINER_ADDED_TO_ITSELF)
集合本身作為add方法的引數,這樣會引起內容溢位。
51.IL: An apparent infinite loop (IL_INFINITE_LOOP)
方法的自呼叫引起的死迴圈
52.IM: Integer multiply of result of integer remainder (IM_MULTIPLYING_RESULT_OF_IREM)
和整數餘數進行乘法運算。例如:i % 60 * 1000 是進行(i % 60) * 1000運算而不是 i % (60 * 1000)
53.INT: Bad comparison of nonnegative value with negative constant (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)
保證非負數和負數進行比較
54.INT: Bad comparison of signed byte (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)
比較有符合數,要先把有符號數轉換為無符合數再進行比較
55.IO: Doomed attempt to append to an object output stream (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)
宣佈試圖在物件的輸出流處新增元素,如果你希望能夠新增進一個物件的輸出流中必須保證物件的輸出流處於開啟狀態。
56.IP: A parameter is dead upon entry to a method but overwritten (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)
The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller.
傳入引數的值被忽略,但是對傳入值進行了修改,並返回給了呼叫者
57.MF: Class defines field that masks a superclass field (MF_CLASS_MASKS_FIELD)
子類中定義了和父類中同名的欄位。在呼叫時會出錯
58.MF: Method defines a variable that obscures a field (MF_METHOD_MASKS_FIELD)
在方法中定義的區域性變數和類變數或者父類變數同名,從而引起欄位混淆。
59.NP: Null pointer dereference (NP_ALWAYS_NULL)
物件賦為null值後 沒有被重新賦值
60.NP: Null pointer dereference in method on exception path (NP_ALWAYS_NULL_EXCEPTION)
A pointer which is null on an exception path is dereferenced here.  This will lead to a NullPointerException when the code is executed.  Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.
Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.
空指標引用上呼叫去除引用方法,將發生空指標異常
61.NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)
方法沒有判斷引數是否為空
62.NP: close() invoked on a value that is always null (NP_CLOSING_NULL)
一個為空的物件呼叫close方法
63.NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)
There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).
在正常的null判斷分支上,物件去除引用操作是受保護的不允許的
64.NP: Value is null and guaranteed to be dereferenced on exception path (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)
There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).


65.NP: Method call passes null to a nonnull parameter (NP_NONNULL_PARAM_VIOLATION)
方法中為null的引數沒有被重新賦值
void test(){
String ss = null;
sya(ss);
}
public void sya(String ad){
ad.getBytes();
}
66.NP: Method may return null, but is declared @NonNull (NP_NONNULL_RETURN_VIOLATION)
方法聲明瞭返回值不能為空,但是方法中有可能返回null
67.NP: A known null value is checked to see if it is an instance of a type (NP_NULL_INSTANCEOF)
檢查一個為null的值是否是想要的型別物件,而不是由於粗心或者邏輯錯誤引起的
68.NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)
物件可能沒有重新賦值
69.NP: Possible null pointer dereference in method on exception path (NP_NULL_ON_SOME_PATH_EXCEPTION)
A reference value which is null on some exception control path is dereferenced here.  This may lead to a NullPointerException when the code is executed.  Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.
Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.
在異常null值處理分支呼叫的方法上,可能存在物件去除引用操作
70.NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)
方法引數中宣告為nonnull型別的引數為null
void test(){
String ss = null;
sya(ss);
}
public void sya(@nonnull String ad){
ad.getBytes();
}
71.NP: Store of null value into field annotated NonNull (NP_STORE_INTO_NONNULL_FIELD)
為一個已經宣告為不能為null值的屬性賦值為null。
72.Nm: Class defines equal(Object); should it be equals(Object)? (NM_BAD_EQUAL)
類中定義了一個equal方法但是卻不是覆寫的Object物件的equals方法
73.Nm: Class defines hashcode(); should it be hashCode()? (NM_LCASE_HASHCODE)
類中定義了一個hashCode方法但是卻不是覆寫的Object中的hashCode方法
74.Nm: Class defines tostring(); should it be toString()? (NM_LCASE_TOSTRING)
類中定義了一個toString方法但是卻不是覆寫的Object中的toString方法
75.Nm: Apparent method/constructor confusion (NM_METHOD_CONSTRUCTOR_CONFUSION)
構造方法定義混亂,保證一個標準的建構函式。例如:
SA(){}
void SA(){
}
76.Nm: Very confusing method names (NM_VERY_CONFUSING)
混亂的方法命名,如getName和getname方法同時出現的時候
77.Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE)
方法因為取了不同包中的同名的物件而沒有正確覆寫父類中的同名方法
import alpha.Foo;
public class A {
  public int f(Foo x) { return 17; }
}
----
import beta.Foo;
public class B extends A {
  public int f(Foo x) { return 42; }
}
78.QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)
再if或者while表示式中使用boolean型別的值時應該使用==去判斷,而不是採用=操作
79.RC: Suspicious reference comparison (RC_REF_COMPARISON)
比較兩個物件值是否相等時應該採用equals方法,而不是==方法
80.RE: Invalid syntax for regular expression (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)
對正則表示式使用了錯誤的語法,會丟擲未經檢查的異常,表明正則表示式模式中的語法錯誤。
81.RE: File.separator used for regular expression (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)
使用正則表示式使用了錯誤的檔案分隔符,在windows系統中正則表示式不會匹配’\’而應該使用'\\'
82.RV: Random value from 0 to 1 is coerced to the integer 0 (RV_01_TO_INT)
從0到1隨機值被強制為整數值0。在強制得到一個整數之前,你可能想得到多個隨機值。或使用Random.nextInt(n)的方法。
83.RV: Bad attempt to compute absolute value of signed 32-bit hashcode (RV_ABSOLUTE_VALUE_OF_HASHCODE)
此程式碼生成一個雜湊碼,然後計算該雜湊碼的絕對值。如果雜湊碼是Integer.MIN_VALUE的,那麼結果將是負數(因為Math.abs(Integer.MIN_VALUE的)== Integer.MIN_VALUE的)。
在2^ 32值之外字串有一個Integer.MIN_VALUE的hashCode包括“polygenelubricants”,“GydZG_”和“,”DESIGNING WORKHOUSES “。
84.RV: Bad attempt to compute absolute value of signed 32-bit random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)
此程式碼生成一個隨機的符號整數,然後計算該隨機整數的絕對值。如果隨機數生成數絕對值為Integer.MIN_VALUE的,那麼結果將是負數(因為Math.abs(Integer.MIN_VALUE的)== Integer.MIN_VALUE的)。
85.RV: Exception created and dropped rather than thrown (RV_EXCEPTION_NOT_THROWN)
此程式碼建立一個異常(或錯誤)的物件,但不會用它做任何事情。例如:if (x < 0)
  new IllegalArgumentException("x must be nonnegative");
這可能是程式設計師的意圖丟擲建立的異常:
if (x < 0)
  throw new IllegalArgumentException("x must be nonnegative");
86.RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)
該方法的返回值應該進行檢查。這種警告通常出現在呼叫一個不可變物件的方法,認為它更新了物件的值。例如:String dateString = getHeaderField(name);
dateString.trim();
程式設計師似乎以為trim()方法將更新dateString引用的字串。但由於字串是不可改變的,trim()函式返回一個新字串值,在這裡它是被忽略了。該程式碼應更正:
String dateString = getHeaderField(name);
dateString = dateString.trim();
87.RpC: Repeated conditional tests (RpC_REPEATED_CONDITIONAL_TEST)
該程式碼包含對同一個條件試驗了兩次,兩邊完全一樣例如:(如X == 0 | | x == 0)。可能第二次出現是打算判斷別的不同條件(如X == 0 | | y== 0)。
88.SA: Double assignment of field (SA_FIELD_DOUBLE_ASSIGNMENT)
方法中的欄位包含了雙重任務,例如: 
 int x;
  public void foo() {
   x = x = 17;
  }
這種為變數賦值是無用的,並可能表明一個邏輯錯誤或拼寫錯誤。
89.SA: Self assignment of field (SA_FIELD_SELF_ASSIGNMENT)
方法中包含自己對自己賦值的欄位。例如:
int x;
  public void foo() {
    x = x;
  }
90.SA: Self comparison of field with itself (SA_FIELD_SELF_COMPARISON)
欄位自己進行自比較可能表明錯誤或邏輯錯誤。
91.SA: Self comparison of value with itself (SA_LOCAL_SELF_COMPARISON)
方法中對一個區域性變數自身進行比較運算,並可說明錯誤或邏輯錯誤。請確保您是比較正確的事情。
92.SA: Nonsensical self computation involving a variable (e.g., x & x) (SA_LOCAL_SELF_COMPUTATION)
此方法對同一變數執行了荒謬的計算(如x&x或x-x)操作。由於計算的性質,這一行動似乎沒有意義,並可能表明錯誤或邏輯錯誤。
93.SF: Dead store due to switch statement fall through (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)
在swtich中先前的case值因為swtich執行失敗而被覆寫,這就像是忘記使用break推出或者沒有使用return語句放回先前的值一樣。
94.SF: Dead store due to switch statement fall through to throw (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW)
在swtich中因為出現異常而忽略了對case值的儲存。
95.SIC: Deadly embrace of non-static inner class and thread local (SIC_THREADLOCAL_DEADLY_EMBRACE)
如果是一個靜態內部類。實際上,在內部類和當前執行緒有死鎖的可能。由於內部類不是靜態的,它保留了對外部類的引用。如果執行緒包含對一個內部類例項的引用,那麼內外例項的例項都可以被獲取,這樣就不具備垃圾會回收的資格。
96.SIO: Unnecessary type check done using instanceof operator (SIO_SUPERFLUOUS_INSTANCEOF)
在進行instanceof操作時進行沒有必要的型別檢查
97.STI: Unneeded use of currentThread() call, to call interrupted() (STI_INTERRUPTED_ON_CURRENTTHREAD)
此方法呼叫Thread.currentThread()呼叫,只需呼叫interrupted()方法。由於interrupted()是一個靜態方法, Thread.interrupted()更簡單易用。
98.STI: Static Thread.interrupted() method invoked on thread instance (STI_INTERRUPTED_ON_UNKNOWNTHREAD)
呼叫不是當前執行緒物件的Thread.interrupted()方法,由於interrupted()方法是靜態的,interrupted方法將會呼叫一個和作者原計劃不同的物件。
99.Se: Method must be private in order for serialization to work (SE_METHOD_MUST_BE_PRIVATE)
這個類實現了Serializable介面,並定義自定義序列化的方法/反序列化。但由於這種方法不能宣告為private,將被序列化/反序列化的API忽略掉。
100.Se: The readResolve method must not be declared as a static method. (SE_READ_RESOLVE_IS_STATIC)
為使readResolve方法得到序列化機制的識別,不能作為一個靜態方法來宣告。
101.UMAC: Uncallable method defined in anonymous class (UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)
在匿名類中定義了一個既沒有覆寫超類中方法也不能直接呼叫的方法。因為在其他類的方法不能直接引用匿名類宣告的方法,似乎這種方法不能被呼叫,這種方法可能只是沒有任何作用的程式碼,但也可能覆寫超類中宣告。
102.UR: Uninitialized read of field in constructor (UR_UNINIT_READ)
此構造方法中使用了一個尚未賦值的欄位或屬性。
String a;
public SA() {
String abc = a;
System.out.println(abc);
}
103.UR: Uninitialized read of field method called from constructor of superclass (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)
方法被超類的建構函式呼叫時,在當前類中的欄位或屬性還沒有被初始化。例如:
abstract class A {
  int hashCode;
  abstract Object getValue();
  A() {
    hashCode = getValue().hashCode();
    }
  }
class B extends A {
  Object value;
  B(Object v) {
    this.value = v;
    }
  Object getValue() {
    return value;
  }
  }
當B是建立時,A的建構函式將在B為value賦值之前觸發,然而在A的初始化方法呼叫getValue方法時value這個變數還沒有被初始化。
104.USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)
該程式碼呼叫上匿名陣列的toString()方法,產生的結果形如[@ 16f0472並沒有實際的意義。考慮使用Arrays.toString方法來轉換成可讀的字串,提供該陣列的內容陣列。例如:
String[] a = { "a" };
System.out.println(a.toString());
//正確的使用為
System.out.println(Arrays.toString(a));
105.USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ARRAY)
該程式碼呼叫上陣列的toString()方法,產生的結果形如[@ 16f0472並不能顯示陣列的真實內容。考慮使用Arrays.toString方法來轉換成可讀的字串,提供該陣列的內容陣列
106.UwF: Field only ever set to null (UWF_NULL_FIELD)
欄位的值總是為null值,所有讀取該欄位的值都為null。檢查錯誤,如果它確實沒有用就刪除掉。
107.UwF: Unwritten field (UWF_UNWRITTEN_FIELD
此欄位是永遠不會寫入值。所有讀取將返回預設值。檢查錯誤(如果它被初始化?),如果它確實沒有用就刪除掉。
五:Performance關於程式碼效能相關方面的
1.Bx: Primitive value is boxed and then immediately unboxed (BX_BOXING_IMMEDIATELY_UNBOXED)
對原始值進行裝箱,然後立即取消裝箱。這可能是在一個未要求裝箱的地方進行了手動裝箱,從而迫使編譯器進行立即撤消裝箱的操作
2.Bx: Primitive value is boxed then unboxed to perform primitive coercion (BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)
對原始值進行裝箱然後立即把它強制轉換為另外一種原始型別。例如:
new Double(d).intValue()應該直接進行強制轉換例如:(int) d
3.Bx: Method allocates a boxed primitive just to call toString (DM_BOXED_PRIMITIVE_TOSTRING)
僅僅為了呼叫封裝類的toString()而對原始型別進行封裝操作。比這種方法更有效的是呼叫封裝類的toString(…)方法例如:
new Integer(1).toString()    替換為   Integer.toString(1)
new Long(1).toString()    替換為   Long.toString(1) 
new Float(1.0).toString()    替換為   Float.toString(1.0) 
new Double(1.0).toString()    替換為   Double.toString(1.0) 
new Byte(1).toString()    替換為   Byte.toString(1) 
new Short(1).toString()    替換為   Short.toString(1) 
new Boolean(true).toString()    替換為   Boolean.toString(true)
4.Bx: Method invokes inefficient floating-point Number constructor; use static valueOf instead (DM_FP_NUMBER_CTOR)
使用new Double(double)方法總是會建立一個新的物件,然而使用Double.valueOf(double)方法可以把值儲存在編輯器或者class library、JVM中。使用儲存值的方式來避免物件的分配可以或得更好的程式碼效能
除非類必須符合Java 1.5以前的JVM,否則請使用自動裝箱或valueOf()方法建立Double和Float例項。
5.Bx: Method invokes inefficient Number constructor; use static valueOf instead (DM_NUMBER_CTOR)
使用new Integer(int)方法總是會建立一個新的物件,然而使用Integer.valueOf(int)方法可以把值儲存在編輯器或者class library、JVM中。使用儲存值的方式來避免物件的分配可以或得更好的程式碼效能
除非類必須符合Java 1.5以前的JVM,否則請使用自動裝箱或valueOf()方法建立Long, Integer, Short, Character, Byte例項。
6.Dm: The equals and hashCode methods of URL are blocking (DMI_BLOCKING_METHODS_ON_URL)
使用equals和hashCode方法來對url進行資源識別符號解析時會引起堵塞。考慮使用java.net.URI來代替。
7.Dm: Maps and sets of URLs can be performance hogs (DMI_COLLECTION_OF_URLS)
方法或者欄位使用url的map/set集合。因為equals方法或者hashCode方法來進行資源識別符號解析時都會引起堵塞。考慮使用java.net.URI來代替。
8.Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead (DM_BOOLEAN_CTOR)
使用new方法建立一個java.lang.Boolean型別能夠的例項物件是浪費空間的,因為Boolean物件是不可變的而且只有兩個有用的值。使用Boolean.valueOf()或者Java1.5中的自動裝箱功能來建立一個Boolean例項。
9.Dm: Explicit garbage collection; extremely dubious except in benchmarking code (DM_GC)
在程式碼中顯式的呼叫垃圾回收命名,這樣做並不能起作用。在過去,有人在關閉操作或者finalize方法中呼叫垃圾回收方法導致了很多的效能浪費。這樣大規模回收物件時會造成處理器執行緩慢。
10.Dm: Use the nextInt method of Random rather than nextDouble to generate a random integer (DM_NEXTINT_VIA_NEXTDOUBLE)
 如果r是一個java.util.Random物件,你可以使r.nextInt(n)生成一個0到n-1之前的隨機數,而不是使用(int)(r.nextDouble() * n)
11.Dm: Method invokes inefficient new String(String) constructor (DM_STRING_CTOR)
使用java.lang.String(String)建構函式會浪費記憶體因為這種構造方式和String作為引數在功能上容易混亂。只是使用String直接作為引數的形式
12.Dm: Method invokes toString() method on a String (DM_STRING_TOSTRING)
呼叫String.toString()是多餘的操作,只要使用String就可以了。
13.Dm: Method invokes inefficient new String() constructor (DM_STRING_VOID_CTOR)
使用沒有引數的構造方法去建立新的String物件是浪費記憶體空間的,因為這樣建立會和空字串“”混淆。Java中保證完成相同的構造方法會產生描繪相同的String物件。所以你只要使用空字串來建立就可以了。
14.ITA: Method uses toArray() with zero-length array argument (ITA_INEFFICIENT_TO_ARRAY)
當使用集合的toArray()方法時使用陣列長度為0的陣列作為引數。比這更有效的一種方法是
myCollection.toArray(new Foo[myCollection.size()]),如果陣列的長度足夠大就可以直接把集合中的內容包裝到陣列中直接返回從而避免了第二次建立一個新的陣列來存放集合中值。
15.SBSC: Method concatenates strings using + in a loop (SBSC_USE_STRINGBUFFER_CONCATENATION)
在迴圈中構建一個String物件時從效能上講使用StringBuffer來代替String物件
例如:
// This is bad
  String s = "";
  for (int i = 0; i < field.length; ++i) {
    s = s + field[i];
  }


  // This is better
  StringBuffer buf = new StringBuffer();
  for (int i = 0; i < field.length; ++i) {
    buf.append(field[i]);
  }
  String s = buf.toString();
16.SS: Unread field: should this field be static? (SS_SHOULD_BE_STATIC)
類中所包含的final屬性欄位在編譯器中初始化為靜態的值。考慮在定義時就把它定義為static型別的。
17.UM: Method calls static Math class method on a constant value (UM_UNNECESSARY_MATH)
在方法中使用了java.lang.Math的靜態方法代替常量來使用,使用常量速度和準確度會更好。 以下為Math中的方法產生的值。
Method Parameter 
abs -any- 
acos 0.0 or 1.0 
asin 0.0 or 1.0 
atan 0.0 or 1.0 
atan2 0.0 cbrt 0.0 or 1.0 
ceil -any- 
cos 0.0 
cosh 0.0 
exp 0.0 or 1.0 
expm1 0.0 
floor -any- 
log 0.0 or 1.0 
log10 0.0 or 1.0 
rint -any- 
round -any- 
sin 0.0 
sinh 0.0 
sqrt 0.0 or 1.0 
tan 0.0 
tanh 0.0 
toDegrees 0.0 or 1.0 
toRadians 0.0
18.UPM: Private method is never called (UPM_UNCALLED_PRIVATE_METHOD)
定義為Private型別方法從未被呼叫,應該被刪除。
19.UrF: Unread field (URF_UNREAD_FIELD)
類中定義的屬性從未被呼叫,建議刪除。
20.UuF: Unused field (UUF_UNUSED_FIELD)
類中定義的屬性從未被使用,建議刪除。
21.WMI: Inefficient use of keySet iterator instead of entrySet iterator (WMI_WRONG_MAP_ITERATOR)
當方法中接受一個Map型別的引數時,使用keySet的迭代器比使用entrySet的迭代器效率要高。
六:Internationalization關於程式碼國際化相關方面的
Dm: Consider using Locale parameterized version of invoked method (DM_CONVERT_CASE)
使用平臺預設的編碼格式對字串進行大小寫轉換,這可能導致國際字元的轉換不當。使用以下方式對字元進行轉換
String.toUpperCase( Locale l )
String.toLowerCase( Locale l )
七:Multithreaded correctness關於程式碼多執行緒正確性相關方面的
1.DL: Synchronization on Boolean could lead to deadlock (DL_SYNCHRONIZATION_ON_BOOLEAN)
該程式碼同步一個封裝的原始常量,例如一個Boolean型別。
private static Boolean inited = Boolean.FALSE;
...
  synchronized(inited) { 
    if (!inited) {
       init();
       inited = Boolean.TRUE;
       }
     }
...
由於通常只存在兩個布林物件,此程式碼可能是同步的其他無關的程式碼中相同的物件,這時會導致反應遲鈍和可能死鎖
2.DL: Synchronization on boxed primitive could lead to deadlock (DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE)
該程式碼同步一個封裝的原始常量,例如一個Integer型別。
private static Integer count = 0;
...
  synchronized(count) { 
     count++;
     }
...
由於Integer物件可以共享和儲存,此程式碼可能是同步的其他無關的程式碼中相同的物件,這時會導致反應遲鈍和可能死鎖
3.DL: Synchronization on interned String could lead to deadlock (DL_SYNCHRONIZATION_ON_SHARED_CONSTANT)
同步String型別的常量時,由於它被JVM中多個其他的物件所共有,這樣在其他程式碼中會引起死鎖。
4.DL: Synchronization on boxed primitive values (DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE)
同步一個顯然不是共有封裝的原始值,例如一個Integer型別的物件。例如:
private static final Integer fileLock = new Integer(1);
...
  synchronized(fileLock) { 
     .. do something ..
     }
...
它最後被定義為以下方式來代替:private static final Object fileLock = new Object();


5.Dm: Monitor wait() called on Condition (DM_MONITOR_WAIT_ON_CONDITION)
方法中以java.util.concurrent.locks.Condition物件呼叫wait()。等待一個條件發生時應該使用在Condition介面中定義的await()方法。
6.Dm: A thread was created using the default empty run method (DM_USELESS_THREAD)
這個方法沒有通過run方法或者具體宣告Thread類,也沒有通過一個Runnable物件去定義一個執行緒,而這個執行緒出來浪費資源卻什麼也沒有去做。
7.ESync: Empty synchronized block (ESync_EMPTY_SYNC)
該程式碼包含一個空的同步塊:synchronized() {}
8.IS: Inconsistent synchronization (IS2_INCONSISTENT_SYNC)
不合理的同步
9.IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)
域不是良好的同步訪問---


此欄位被標註為net.jcip.annotations.GuardedBy,但可以在某種程度上違反註釋而去訪問
10.JLM: Synchronization performed on Lock (JLM_JSR166_LOCK_MONITORENTER)
實現java.util.concurrent.locks.Lock的物件呼叫了同步的方法。應該這樣處理,物件被鎖定/解鎖時使用acquire()/ release()方法而不是使用同步的方法。
11.LI: Incorrect lazy initialization of static field (LI_LAZY_INIT_STATIC)
靜態域不正確的延遲初始化--
這種方法包含了一個不同步延遲初始化的非volatile靜態欄位。因為編譯器或處理器可能會重新排列指令,如果該方法可以被多個執行緒呼叫,執行緒不能保證看到一個完全初始化的物件。你可以讓欄位可變來解決此問題
12.LI: Incorrect lazy initialization and update of static field (LI_LAZY_INIT_UPDATE_STATIC)
這種方法包含一個不同步延遲初始化的靜態欄位。之後為欄位賦值,物件儲存到該位置後進一步更新或訪問。欄位後儘快讓其他執行緒能夠訪問。如果該方法的進一步訪問該欄位為初始化物件提供服務,然後你有一個非常嚴重的多執行緒bug,除非別的東西阻止任何其他執行緒訪問儲存的物件,直到它完全初始化。
即使你有信心,該方法是永遠不會被多個執行緒呼叫時,在它的值還沒有被充分初始化或移動,不把它設定為static欄位時它可能會更好。
13.ML: Method synchronizes on an updated field (ML_SYNC_ON_UPDATED_FIELD)
物件獲取一個可變欄位時進行同步。這是沒有意義的,因為不同的執行緒可以在不同的物件同步。
14.MSF: Mutable servlet field (MSF_MUTABLE_SERVLET_FIELD)
一個web服務一般只能建立一個servlet或者jsp的例項(例如:treates是一個單利類),它會被多個執行緒呼叫這個例項的方法服務於多個同時的請求。因此使用易變的欄位屬性產生競爭的情況。
15.MWN: Mismatched notify() (MWN_MISMATCHED_NOTIFY)
此方法呼叫Object.notify()或Object.notifyAll()而沒有獲取到該物件的物件鎖。呼叫notify()或notifyAll()而沒有持有該物件的物件鎖,將導致IllegalMonitorStateException異常。
16.MWN: Mismatched wait() (MWN_MISMATCHED_WAIT)
此方法呼叫Object.wait()而沒有獲取到該物件的物件鎖。呼叫wait()而沒有持有該物件的物件鎖,將導致IllegalMonitorStateException異常。
17.NP: Synchronize and null check on the same field. (NP_SYNC_AND_NULL_CHECK_FIELD)
如果程式碼塊是同步的,那麼久不可能為空。如果是空,同步時就會丟擲NullPointerException異常。最好是在另一個程式碼塊中進行同步。
18.No: Using notify() rather than notifyAll() (NO_NOTIFY_NOT_NOTIFYALL)
呼叫notify()而不是notifyAll()方法。 Java的監控器通常用於多個條件。呼叫notify()只喚醒一個執行緒,這意味著該執行緒被喚醒只是滿足的當前的唯一條件。
19.RS: Class's readObject() method is synchronized (RS_READOBJECT_SYNC)
序列化類中定義了同步的readObject()。通過定義,反序列化建立的物件只有一個執行緒可以訪問,因此沒有必要的readObject()進行同步。如果的readObject()方法本身造成物件對另一個執行緒可見,那麼這本身就是不好的編碼方式。
20.Ru: Invokes run on a thread (did you mean to start it instead?) (RU_INVOKE_RUN)
這種方法顯式呼叫一個物件的run()。一般來說,類是實現Runnable介面的,因為在一個新的執行緒他們將有自己的run()方法,在這種情況下Thread.start()方法呼叫是正確的。
21.SC: Constructor invokes Thread.start() (SC_START_IN_CTOR)
在建構函式中啟動一個執行緒。如果類曾經被子類擴充套件過,那麼這很可能是錯的,因為執行緒將在子類構造之前開始啟動。
22.SP: Method spins on field (SP_SPIN_ON_FIELD)
方法無限迴圈讀取一個欄位。編譯器可合法懸掛宣讀迴圈,變成一個無限迴圈的程式碼。這個類應該改變,所以使用適當的同步(包括等待和通知要求)
23.STCAL: Call to static Calendar (STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)
即使JavaDoc對此不包含暗示,而Calendars本身在多執行緒中使用就是不安全的。探測器發現當呼叫Calendars的例項時將會獲得一個靜態物件。
Calendar rightNow = Calendar.getInstance();
24.STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)
在官方的JavaDoc,DateFormats多執行緒使用本事就是不安全的。探測器發現呼叫一個DateFormat的例項將會獲得一個靜態物件。
myString = DateFormat.getDateInstance().format(myDate);


25.STCAL: Static Calendar (STCAL_STATIC_CALENDAR_INSTANCE)
Calendar在多執行緒中本身就是不安全的,如果線上程範圍中共享一個Calendarde 例項而不使用一個同步的方法在應用中就會出現一些奇怪的行為。在sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate()中會丟擲ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions異常。
26.STCAL: Static DateFormat (STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)
DateFormat 在多執行緒中本身就是不安全的,如果線上程範圍中共享一個DateFormat的例項而不使用一個同步的方法在應用中就會出現一些奇怪的行為。
27.SWL: Method calls Thread.sleep() with a lock held (SWL_SLEEP_WITH_LOCK_HELD)
當持有物件時呼叫Thread.sleep()。這可能會導致很差的效能和可擴充套件性,或陷入死鎖,因為其他執行緒可能正在等待獲得鎖。呼叫wait()是一個更好的主意,釋放物件的持有以允許其他執行緒執行。
28.UG: Unsynchronized get method, synchronized set method (UG_SYNC_SET_UNSYNC_GET)
這個類包含類似命名的get和set方法。在set方法是同步方法和get方法是非同步方法。這可能會導致在執行時的不正確行為,因為呼叫的get方法不一定返回物件一致狀態。 GET方法應該同步。
29.UL: Method does not release lock on all paths (UL_UNRELEASED_LOCK)
方法獲得了當前的物件所,但是在方法中始終沒有釋放它。一個正確的示例如下:
  Lock l = ...;
    l.lock();
    try {
        // do something
    } finally {
        l.unlock();
    }
30.UL: Method does not release lock on all exception paths (UL_UNRELEASED_LOCK_EXCEPTION_PATH)
方法獲得了當前的物件所,但是在所有的異常處理中始終沒有釋放它。一個正確的示例如下:
  Lock l = ...;
    l.lock();
    try {
        // do something
    } finally {
        l.unlock();
    }
31.UW: Unconditional wait (UW_UNCOND_WAIT)
方法中包含呼叫java.lang.Object.wait(),而卻沒有放到條件流程控制中。該程式碼應確認條件尚未滿足之前等待;先前任何通知將被忽略。
32.VO: A volatile reference to an array doesn't treat the array elements as volatile (VO_VOLATILE_REFERENCE_TO_ARRAY)
宣告一個變數引用陣列,這可能不是你想要的。如果一個變數引用陣列,那麼對引用陣列的讀和寫都是不安全的,但是陣列元素不是變數。取得陣列的變數值你可以使用java.util.concurrent包中的陣列的原子性特性
33.WL: Sychronization on getClass rather than class literal (WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)
例項的方法中同步this.getClass(),如果這個類有子類集合,那麼子類集合中的物件將會在這個類的各個子類上進行同步,這不是我們想要的效果,我們只要同步當前的類物件而不包含它的所有子類,可以同步類名.getClass()。例如,java.awt.Label的程式碼:
     private static final String base = "label";
     private static int nameCounter = 0;
     String constructComponentName() {
        synchronized (getClass()) {
            return base + nameCounter++;
        }
     }
Label中的子類集合不可能在同一個子物件上進行同步,替換上面的方法為:
    private static final String base = "label";
     private static int nameCounter = 0;
     String constructComponentName() {
        synchronized (Label.class) {
            return base + nameCounter++;
        }
     }
34.WS: Class's writeObject() method is synchronized but nothing else is (WS_WRITEOBJECT_SYNC)
這個類有一個writeObject()方法是同步的,但是這個類中沒有其他的同步方法。
35.Wa: Condition.await() not in loop (WA_AWAIT_NOT_IN_LOOP)
方法沒有在迴圈中呼叫java.util.concurrent.await()。如果物件是用於多種條件,打算呼叫wait()方法的條件可能不是實際發生的。
36.Wa: Wait not in loop (WA_NOT_IN_LOOP)
這種方法包含呼叫java.lang.Object.wait(),而這並不是一個迴圈。如果監視器用於多個條件,打算呼叫wait()方法的條件可能不是實際發生的。
八:Malicious codevulnerability關於惡意破壞程式碼相關方面的
1.EI: May expose internal representation by returning reference to mutable object (EI_EXPOSE_REP)
返回一個易變物件引用並把它儲存在物件欄位中時會暴露物件內部的欄位描述,如果接受不守信任的程式碼訪問或者沒有檢查就去改變易變物件的會涉及物件的安全和其他重要屬性的安全。返回一個物件的新副本,在很多情況下更好的辦法。
2.EI2: May expose internal representation by incorporating reference to mutable object (EI_EXPOSE_REP2)
此程式碼把外部可變物件引用儲存到物件的內部表示。如果例項受到不信任的程式碼的訪問和沒有檢查的變化危及物件和重要屬性的安全。儲存一個物件的副本,在很多情況下是更好的辦法。
3.FI: Finalizer should be protected, not public (FI_PUBLIC_SHOULD_BE_PROTECTED)
一個類中的finalize()方法必須宣告為protected,而不能為public型別
4.MS: Public static method may expose internal representation by returning array (MS_EXPOSE_REP)
一個public型別的靜態方法返回一個數組,可能引用內部屬性的暴露。任何程式碼呼叫此方法都可以自由修改底層陣列。一個解決辦法是返回一個數組的副本。
5.MS: Field should be both final and package protected (MS_FINAL_PKGPROTECT)
一個靜態欄位可能被惡意程式碼或另外一個包所改變的。欄位可以放到protected包中也可以定義為final型別的以避免此問題。
6.MS: Field is a mutable array (MS_MUTABLE_ARRAY)
一個定義為final型別的靜態欄位引用一個數組時它可以被惡意程式碼或在另其他包中所使用。這些程式碼可以自由修改陣列的內容。
7.MS: Field is a mutable Hashtable (MS_MUTABLE_HASHTABLE)
一個定義為final型別的靜態欄位引用一個Hashtable時可以被惡意程式碼或者在其他包中被呼叫,這些方法可以修改Hashtable的值。
8.MS: Field should be moved out of an interface and made package protected (MS_OOI_PKGPROTECT)
將域儘量不要定義在介面中,並宣告為包保護
在介面中定義了一個final型別的靜態欄位,如陣列或雜湊表等易變物件。這些物件可以被惡意程式碼或者在其他包中被呼叫,為了解決這個問題,需要把它定義到一個具體的實體類中並且宣告為保護型別以避免這種錯誤。
9.MS: Field should be package protected (MS_PKGPROTECT)
一個靜態欄位是可以改變的惡意程式碼或其他的包訪問修改。可以把這種型別的欄位宣告為final型別