在使用 Jenkins 構建 Java Web 項目時候,有一項叫做靜態代碼檢查,是用內置的 findBugs 插件,對程序源代碼進行檢查,以分析程序行為的技術,應用於程序的正確性檢查、
安全缺陷檢測、程序優化等,特點就是不執行程序。它有助於在項目早期發現以下問題:變量聲明了但未使用、變量類型不匹配、變量在使用前未定義、不可達代碼、死循環、數組越界、內存泄漏等。分為以下幾種類型:
一、Bad Practice (糟糕的寫法)
二、Correctness (不太的當)
三、Experimental (實驗)
四、Internationalization (國際化)
五、Malicious code vulnerability (有漏洞的代碼)
六、Multithreaded correctness (多線程問題)
七、Performance (執行)
八、Security (安全性)
九、Dodgy code (可疑代碼)
具體描述,可以參加如下地址:問題列表以及描述
常見的比如:
SBSC: Method concatenates strings using + in a loop (SBSC_USE_STRINGBUFFER_CONCATENATION)
問題描述已經很清楚了,盡量不要在循環中使用 String,用 StringBuffer 來代替:
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.
Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.
For example:
// 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();
寫段代碼比較下:
1 Long preSecond = System.currentTimeMillis(); 2 String str = ""; 3 int length = 10000; 4 for (int i = 0; i < length; i++) { 5 str += i; 6 } 7 System.out.println("cost " + (System.currentTimeMillis() - preSecond) + " seconds."); 8 Long posSecond = System.currentTimeMillis(); 9 StringBuffer buffer = new StringBuffer(); 10 for (int i = 0; i < length; i++) { 11 buffer.append(i); 12 } 13 System.out.println("cost " + (System.currentTimeMillis() - posSecond) + " seconds.");
輸出結果為:
cost 363 seconds.
cost 3 seconds.
還有個錯誤關於實體類的setter和getter方法的:
EI2: May expose internal representation by incorporating reference to mutable object (EI_EXPOSE_REP2)
This code stores a reference to an externally mutable object into the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.
報的是這種比如Date類型的字段的getter和setter方法:
這里的警告意思是,在進行get或者set時候,因為 Java 是引用傳遞,對象之間賦值,可能會導致其他對象的修改,所以建議的做法是,把對象的克隆對象賦值給需要賦值的對象。
首先,該實體類要繼承 Cloneable 接口,然后在對應的 getter 和 setter 方法更改如下即可:
在一款優秀的 Java IDE —— IntellijIDEA 中,也可以安裝對應的插件,來將這些問題扼殺在項目上線之前,避免不必要的麻煩。
安裝以后,右擊要分析的Java文件,選擇Analyzed Files 即可
分析之后,如果有bugs,就會顯示,然后根據提示來修正即可