FindBugs:Java 靜態程式碼檢查

shaopiing發表於2016-08-14

在使用 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,就會顯示,然後根據提示來修正即可

相關文章