FindBugs —— Java 靜態代碼檢查

來源:互聯網
上載者:User

標籤:

在使用 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.

 

在一款優秀的 Java IDE —— IntellijIDEA 中,也可以安裝對應的外掛程式,來將這些問題扼殺在項目上線之前,避免不必要的麻煩。

安裝以後,右擊要分析的Java檔案,選擇Analyzed Files 即可

分析之後,如果有bugs,就會顯示,然後根據提示來修正即可

FindBugs —— Java 靜態代碼檢查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.