代碼掃描問題以及解決方式(轉載備忘)

 

原文地址:https://blog.csdn.net/wwbmyos/article/details/50549650

 

1、LI_LAZY_INIT_UPDATE_STATIC:Incorrect lazy initialization and update of static field

 

Thismethod contains an unsynchronized lazy initialization of a static field. Afterthe field is set, the object stored into that location is further updated oraccessed. The setting of the field is visible to other threads as soon as it isset. If the futher accesses in the method that set the field serve toinitialize the object, then you have a veryseriousmultithreading bug, unless something else prevents any otherthread from accessing the stored object until it is fully initialized.

 

原因分析:

 

該方法的初始化中包含了一個遲緩初始化的靜態變量。你的方法引用了一個靜態變量,估計是類靜態變量,那麼多線程調用這個方法時,你的變量就會面臨線程安全的問題了,除非別的東西阻止任何其他線程訪問存儲對象從直到它完全被初始化。

 

解決方法:給該方法加上synchronized同步鎖,並且給有調用到該靜態變量的方法也加上synchronized同步鎖。

 

2、RR_NOT_CHECKED: Method ignores results ofInputStream.read()

 

This method ignores the return value ofone of the variants of java.io.InputStream.read() which can returnmultiple bytes. If the return value is not checked, the caller will notbe able to correctly handle the case where fewer bytes were read than thecaller requested. This is a particularly insidious kind of bug, becausein many programs, reads from input streams usually do read the full amount ofdata requested, causing the program to fail only sporadically.

 

原因分析:

 

InputStream.read方法忽略返回的多個字符,如果對結果沒有檢查就沒法正確處理用戶讀取少量字符請求的情況。

 

解決方法:定義一個變量接收該方法返回值,如while((number = is.read(bs))!= -1) {}

 

3、RV_RETURN_VALUE_IGNORED_BAD_PRACTICE:Method ignores exceptional return value

 

This methodreturns a value that is not checked. The return value should be checked sinceit can indicate an unusual or unexpected function execution. For example, the File.delete() methodreturns false if the file could not be successfully deleted (rather thanthrowing an Exception). If you don't check the result, you won't notice if themethod invocation signals unexpected behavior by returning an atypical returnvalue.

 

原因分析:方法忽略返回值的異常信息

 

解決方法:

 

原代碼:if (file.exists()) {

 

    file.delete();

 

   }

 

修改後的代碼:try {

 

     file.delete();

 

    }catch(SecurityException e){

 

     Utils.logger.info(e);

 

    }catch(NullPointerException e){

 

     Utils.logger.info(e);

 

    }

 

4、SE_BAD_FIELD:Non-transient non-serializable instance field in serializable class

 

This Serializableclass defines a non-primitive instance field which is neither transient,Serializable, or java.lang.Object, and does not appear to implement theExternalizable interfaceor the readObject() and writeObject() methods. Objects of this class will not be deserialized correctly if a non-Serializableobject is stored in this field.

 

原因分析:序列化的類裏面定義了一個非序列化的字段

 

解決方法:給該字段加上transient表明這是一個序列化字段

 

5、NP_NULL_ON_SOME_PATH_EXCEPTION:Possible null pointer dereference in method on exception path

 

Areference value which is null on some exception control path is dereferencedhere. This may lead to a NullPointerException when the code isexecuted. Note that because FindBugs currently does not prune infeasibleexception paths, this may be a false warning.

 

Alsonote that FindBugs considers the default case of a switch statement to be anexception path, since the default case is often infeasible.

 

原因分析:有些代碼可能會發生空指針異常

 

解決方法:進行判空就好了

 

6、NP_NULL_PARAM_DEREF:Method call passes null for nonnull parameter

 

Thismethod call passes a null value for a nonnull method parameter. Either theparameter is annotated as a parameter that should always be nonnull, oranalysis has shown that it will always be dereferenced

 

原因分析:對參數爲空的未進行處理

 

解決方法:進行判空就好了

 

7、NP_NULL_ON_SOME_PATH:Possible null pointer dereference

 

Thereis a branch of statement that, if executed, guarantees that a nullvalue will be dereferenced, which would generate a NullPointerException whenthe code is executed. Of course, the problem might be that the branch orstatement is infeasible and that the null pointer exception can't ever beexecuted; deciding that is beyond the ability of FindBugs

 

原因分析:可能存在空的引用

 

解決方法:要麼判空,要麼註釋掉,如System.out等

 

8、NP_UNWRITTEN_FIELD:Read of unwritten field

 

Theprogram is dereferencing a field that does not seem to ever have a non-nullvalue written to it. Dereferencing this value will generate a null pointerexception.

 

原因分析:此字段是永遠不會寫入值,如果不需要的話就刪除掉

 

解決方法:要麼複製,要麼註釋掉

 

9、DMI_INVOKING_TOSTRING_ON_ARRAY:Invocation of toString on an array

 

Thecode invokes toString on an array, which will generate a fairly useless resultsuch as [C@16f0472. Consider using Arrays.toString to convert the array into areadable String that gives the contents of the array. See Programming Puzzlers,chapter 3, puzzle 12.

 

原因分析:該代碼調用上數組的toString()方法,產生的結果形如[@ 16f0472並不能顯示數組的真實內容。

 

解決方法:用Arrays.toString方法或者new String(X,“gbk”)來轉換

 

10、UWF_UNWRITTEN_FIELD:Unwritten field

 

Thisfield is never written. All reads of it will return the default value.Check for errors (should it have been initialized?), or remove it if it isuseless

 

原因分析:該字段從未被賦值過

 

解決辦法:要麼註釋掉該字段,要麼給它初始化

 

11、RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE:Redundant nullcheck of value known to be non-null

 

Thismethod contains a redundant check of a known non-null value against theconstant null.

 

原因分析:方法中包含沒有檢查可能爲空的地方

 

解決辦法:先檢查是否爲空再進行相關操作

 

12、EI_EXPOSE_REP:May expose internal representation by returning reference to mutable object

 

Returninga reference to a mutable object value stored in one of the object's fieldsexposes the internal representation of the object. If instances are accessed by untrusted code,and unchecked changes to the mutable object would compromise security or otherimportant properties, you will need to do something different. Returning a newcopy of the object is better approach in many situations.

 

原因分析:返回一個易變對象引用並把它保存在對象字段中時會暴露對象內部的字段描述,如果接受不守信任的代碼訪問或者沒有檢查就去改變易變對象的會涉及對象的安全和其他重要屬性的安全。返回一個對象的新副本,在很多情況下更好的辦法。在編寫JavaBean時,如果類內部的成員變量爲一個對象類型,就有可能產生這種情況。

 

解決方法:

 

源代碼:

 

publicclass StudentBean

 

{

 

       private Date addDate;

 

       public Date getAddDate()

 

       {

 

              return addDate;

 

       }

 

}

 

修改後的代碼:

 

publicclass StudentBean

 

{

 

       private Date addDate;

 

 

 

       public Date getAddDate()

 

       {

 

              if (addDate == null)

 

              {

 

                     return null;

 

              }

 

              return (Date)addDate.clone();

 

       }

 

}

 

13、EI_EXPOSE_REP2:May expose internal representation by incorporating reference to mutable object

 

Thiscode stores a reference to an externally mutable object into the internalrepresentation of the object. Ifinstances are accessed by untrusted code, and unchecked changes to the mutableobject would compromise security or other important properties, you will needto do something different. Storing a copy of the object is better approach inmany situations.

 

原因分析:此代碼把外部可變對象引用存儲到對象的內部表示。如果實例受到不信任的代碼的訪問和沒有檢查的變化危及對象和重要屬性的安全。存儲一個對象的副本,在很多情況下是更好的辦法。

 

解決方法:

 

源代碼:

 

publicclass StudentBean

 

{

 

       private Date addDate;

 

       public void setAddDate(Date addDate)

 

       {

 

              this.addDate = addDate;

 

       }

 

}

 

修改後的代碼:

 

publicclass StudentBean

 

{

 

       private Date addDate;

 

       public void setAddDate(Date addDate)

 

       {

 

              if (addDate == null)

 

              {

 

                     this.addDate = null;

 

              } else {

 

                     this.addDate =(Date)addDate.clone();

 

              }

 

       }

 

}

 

14、IS2_INCONSISTENT_SYNC:Inconsistent synchronization

 

Thefields of this class appear to be accessed inconsistently with respect tosynchronization. This bug reportindicates that the bug pattern detector judged that

 

 

 

Theclass contains a mix of locked and unlocked accesses,

 

Atleast one locked access was performed by one of the class's own methods, and

 

Thenumber of unsynchronized field accesses (reads and writes) was no more than onethird of all accesses, with writes being weighed twice as high as reads

 

Atypical bug matching this bug pattern is forgetting to synchronize one of themethods in a class that is intended to be thread-safe.

 

 

 

Youcan select the nodes labeled "Unsynchronized access" to show the codelocations where the detector believed that a field was accessed withoutsynchronization.

 

 

 

Notethat there are various sources of inaccuracy in this detector; for example, thedetector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate indistinguishing locked vs. unlocked accesses, the code in question may still becorrect.

 

原因分析:沒有同步

 

解決方法:涉及到該字段的方法都加上synchronized

 

15、OBL_UNSATISFIED_OBLIGATION:Method may fail to clean up stream or resource

 

Thismethod may fail to clean up (close, dispose of) a stream, database object, orother resource requiring an explicit cleanup operation.

 

 

 

Ingeneral, if a method opens a stream or other resource, the method should use atry/finally block to ensure that the stream or resource is cleaned up beforethe method returns.

 

 

 

Thisbug pattern is essentially the same as the OS_OPEN_STREAM andODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (andhopefully better) static analysis technique. We are interested is gettingfeedback about the usefulness of this bug pattern.

 

原因分析:這種方法可能無法清除(關閉,處置)一個流,數據庫對象,或其他資源需要一個明確的清理行動。一般來說,如果一個方法打開一個流或其他資源,該方法應該使用try /finally塊來確保在方法返回之前流或資源已經被清除了。這種錯誤模式基本上和OS_OPEN_STREAM和ODR_OPEN_DATABASE_RESOURCE錯誤模式相同,但是是在不同在靜態分析技術。

 

解決方法:流的關閉都寫在finally裏面

 

16、DM_NUMBER_CTOR:Method invokes inefficient Number constructor; use static valueOf instead

 

Usingnew Integer(int) is guaranteed to always result in a new object whereasInteger.valueOf(int) allows caching of values to be done by the compiler, classlibrary, or JVM. Using of cached values avoids object allocation and the codewill be faster.Values between -128 and 127 are guaranteed to have correspondingcached instances and using valueOf is approximately 3.5 times faster than usingconstructor. For values outside the constant range the performance of bothstyles is the same.Unless the class must be compatible with JVMs predating Java1.5, use either autoboxing or the valueOf() method when creating instances ofLong, Integer, Short, Character, and Byte.

 

原因分析:使用new Integer(int)方法總是會創建一個新的對象,然而使用Integer.valueOf(int)方法可以把值保存在編輯器或者classlibrary、JVM中。使用存儲值的方式來避免對象的分配可以或得更好的代碼性能除非類必須符合Java1.5以前的JVM,否則請使用自動裝箱或valueOf()方法創建Long, Integer,Short, Character, Byte實例。

 

解決方法:Integer創建時把new Integer改成Integer.valueOf

 

17、DM_NEXTINT_VIA_NEXTDOUBLE:Use the nextInt method of Random rather than nextDouble to generate a randominteger if r is a java.util.Random, you can generate a randomnumber from 0 to n-1 using r.nextInt(n), rather thanusing (int)(r.nextDouble() * n).

 

原因分析:如果r是一個java.util.Random對象,你可以使r.nextInt(n)生成一個0到n-1之前的隨機數,而不是使用(int)(r.nextDouble()* n)

 

解決方法:分析已經說的很明顯了

 

18、SBSC_USE_STRINGBUFFER_CONCATENATION:Method concatenates strings using + in a loop

 

Themethod seems to be building a String using concatenation in a loop. In eachiteration, the String is converted to a StringBuffer/StringBuilder, appendedto, and converted back to a String. This can lead to a cost quadratic in thenumber of iterations, as the growing string is recopied in each iteration.

 

Better performance can be obtained by using aStringBuffer (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 = newStringBuffer();

 

  for (int i = 0; i <field.length; ++i) {

 

    buf.append(field[i]);

 

  }

 

  String s = buf.toString();

 

19、SS_SHOULD_BE_STATIC:Unread field: should this field be static?

 

Thisclass contains an instance final field that is initialized to a compile-timestatic value. Consider making the field static.

 

原因分析:類中所包含的final屬性字段在編譯器中初始化爲靜態的值。考慮在定義時就把它定義爲static類型的。

 

解決方法:final的字段可以定義爲static類型

 

20、URF_UNREAD_FIELD:Unread field

 

Thisfield is never read. Consider removing it from the class.

 

原因分析:字段沒有被使用過,可以註釋掉

 

解決方法:刪掉或者註釋掉

 

21、DB_DUPLICATE_BRANCHES:Method uses the same code for two branches

 

Thismethod uses the same code to implement two branches of a conditional branch.Check to ensure that this isn't a coding mistake

 

原因分析:兩個不同分支使用了相同代碼

 

解決方法:代碼優化合並

 

22、DLS_DEAD_LOCAL_STORE:Dead store to local variable

 

Thisinstruction assigns a value to a local variable, but the value is not read orused in any subsequent instruction. Often, this indicates an error, because thevalue computed is never used.Note that Sun's javac compiler often generatesdead stores for final local variables. Because FindBugs is a bytecode-basedtool, there is no easy way to eliminate these false positives.

 

原因分析:該指令爲局部變量賦值,但在其後的沒有對她做任何使用。通常,這表明一個錯誤,因爲值從未使用過。

 

解決方法:代碼優化註釋掉

 

23、IM_BAD_CHECK_FOR_ODD:Check for oddness that won't work for negative numbers

 

Thecode uses x % 2 == 1 to check to see if a value is odd, but this won't work fornegative numbers (e.g., (-5) % 2 == -1). If this code is intending to check foroddness, consider using x & 1 == 1, or x % 2 != 0.

 

原因分析:如果row是負奇數,那麼row % 2 ==-1

 

解決方法:如上所示

 

24、NP_DEREFERENCE_OF_READLINE_VALUE:Dereference of the result of readLine() without nullcheck

 

Theresult of invoking readLine() is dereferenced without checking to see if theresult is null. If there are no more lines of text to read, readLine() willreturn null and dereferencing that will generate a null pointer exception.

 

原因分析:對readLine()的結果值沒有進行判空操作就去重新賦值,這樣的操作可以會拋出空指針異常

 

解決方法:

 

對readLine()的結果值沒有進行判空操作就去重新賦值,這樣的操作可以會拋出空指針異常

 

解決方法:當要對readLine方法進行操作的時候判個空先

 

25、REC_CATCH_EXCEPTION:Exception is caught when Exception is not thrown

 

Thismethod uses a try-catch block that catches Exception objects, but Exception isnot thrown within the try block, and RuntimeException is not explicitly caught.It is a common bug pattern to say try { ... } catch (Exception e) { something }as a shorthand for catching a number of types of exception each of whose catchblocks is identical, but this construct also accidentally catchesRuntimeException as well, masking potential bugs.

 

原因分析:在try/catch塊中捕獲異常,但是異常沒有在try語句中拋出而RuntimeException又沒有明確的被捕獲。這麼寫會無意中把RuntimeException也捕獲了,有可能導致潛在的bug。 JVM對RuntimeException有統一的捕獲機制,讓JVM來處理。

 

解放方法:只需要捕獲具體的異常信息即可,嫑把所有異常都拋給Exception,java並不推薦這麼做。如:

 

源代碼:catch (Exception e) {

 

               return l8Date;

 

           }

 

修改後的代碼:catch(UnsupportedEncodingException e){

 

   Utils.logger.error("積分明細查詢,調用1017報文接口異常!");

 

    returnUtils.makeErrorResponse("");

 

   }

 

26、ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD: Write to staticfield from instance method

 

Thisinstance method writes to a static field. This is tricky to get correct ifmultiple instances are being manipulated, and generally bad practice.

 

原因分析:靜態私有的成員變量不能在public類裏面直接賦值,最好是通過get/set方法進行操作。一般常見於常量類,直接通過類名.常量名獲取的方式違背了封裝的原則,findbugs不提倡使用,而如果將常量改成靜態成員變量,又因爲spring不支持靜態注入導致不能實現,解決方法是非靜態的setter調用靜態的setter方法給靜態成員變量賦值。

 

解決方法:通過get/set方法提供操作

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章