FindBugs error type and corresponding explanation _ tool

Source: Internet
Author: User
Tags instance method readable volatile


FindBugs error type and corresponding explanation first bomb


1, the Dead store to the local variable variables store unused objects
Example:
List accountcolist = new ArrayList ();
We created a new object for Accountcolist, but the new object was not used behind the program.
Proposed to read:
List accountcolist = null;

2, write to static field from instance method writes values to the static field
Example:
private static Dbrbo Dbrbo;
Public final void Refresh () {
DANSKEBANKBO = null;
Dbrbo = null;
FILEANDPATHBO = null;
}
Proposed to read:
Remove the static.


3. Load of known null value generally means an object that is loaded with null.
Example
if (null = = Bolist) {

for (int i = 0; i < bolist.size (); i++) {
Entitylist.add (Productbotoentity (Bolist.get (i)));
}
}


4, Exception is caught when Exception isn't thrown it's better to understand: it's a catch. But there's no exception thrown in try


5, methods ignores exceptional return value does not check the method's exception returns


6. Comparison of String objects using = = or!=
This code compares java.lang.String objects for reference equality using the = = or!= operators.
Unless both strings are either constants in a source file, or have been using the interned () method,
The same string value may is represented by two different string objects. Consider using the Equals (Object) method
instead.
The literal meaning can be understood when a string object is compared: there are only two situations where you can use = = or!=, either as a constant in the source file or as a call to the
The String.intern () method, which is compared using the canonical representation of string, is recommended if it is not in both cases. Equals (object)

7, methods names should start with a lower case letter this is a good understanding of the method name first letters cannot be uppercase

8, Non-transient non-serializable instance field in serializable class
This Serializable class defines a non-primitive instance field which is neither transient, Serializable,
Or Java.lang.Object, and does not appear to implement the Externalizable interface or the ReadObject ()
and WriteObject () methods.? Objects of this class won't be deserialized correctly if a Non-serializable object
is stored in the This field.


This error means that there is data that cannot be serialized or can not be staged in a serializable class


FindBugs error type and corresponding explanation second bullet

1, Bug:hard coded reference to a absolute pathname    Bug Description: This code constructs a File object using a Hard Co Ded to a absolute pathname (this code contains the file object as an absolute pathname)      problem reason: Hard coded point to absolute path.     File prefile = new file (Preferences_file_full_path);     and private static final String Preferences_file_full_path =        /data/data/com  . Android.mms/shared_prefs/auto_download.xml ";   Preferences_file_full_path declared for final type, immutable. The problem is introduced if subsequent file paths are changed, the references are not available, but the paths are not changed.   Solution: Remove Final.   2, Bug:Pattern:Dead store to local variable   BUG Description: This instruction assigns a-value to a local variable, but The ' value is ' not ' read or used in any subsequent instruction. Often, this indicates a error, because the value computed is never used. (the directive assigns a value to a local variable, but does not do anything with her thereafter.) Typically, this indicates an error because the value has never been used.   Problem Reason: The lock screen prompts dead store to Velocityx, the analysis Code   Case MOTIONEVENT.ACTION_POINTER_1_UP statement defines the local variable Velocityx, and only in the IF ( (Mdirectionflag && velOcityx > 0) | | (!mdirectionflag && Velocityx < 0)) Velocityx =-velocityx is not used again after assigning value. Therefore there is no need to assign the value, and the analysis code does not need the variable and can be removed.   Solution: Remove the definition of Velocityx variable and assign value.   3, Bug:inconsistent synchronization BUG Description: The fields of this class appear to is accessed inconsistently with Respec T to synchronization. (unreasonable sync)   problem reason: According to the description Configloader file Munlockappdatamap in 46% of the time is in the locked state. Parsing code Munlockappdatamap is locked in the Checkunlockappconfigchange function. The method public synchronized Boolean Checkunlockappconfigchange (the context context) has no local invocation.   Solution: Remove the Synchronized keyword.   4, Bug:incorrect lazy initialization of static field   BUG Description: This method contains a unsynchronized lazy Alization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are don't guaranteed to a completely initialized obj ECT, if the can is called by multiple threads. (This method includes a non-volatile static field that does not synchronize delay initialization.) Because the compiler or processor may rearrange instructions, the thread cannot guarantee that a fully initialized object is seen if the method can be invoked by multiple threads.   Problem Reason: sinstanceis a static type, the clean () method may be invoked by multiple threads, which may be problematic when sinstance is judged to be non-empty.   Workaround: Clean () plus keyword synchronized. public static synchronized void Clean ()   5, bug:redundant Nullcheck of value Known to IS non-null   Bug Description: This method contains a redundant check of a known Non-null value against the constant LL. (the method makes null judgments about values that are not NULL.)   Problem Reason: Analysis FindBugs error This code   if (Minputstream = = null) {  LOG.I (TAG, "Minputstream is null");   return;  }   Mdbuilder = Mdbuilderfactory.newdocumentbuilder ();   if (Minputstream!= null) {  mdocument = Mdbuilder.parse (minputstream);  }else {  LOG.I (TAG, "mIn Putstream = =  null ");   return;  }   Minputstream if NULL, it is returned directly. There is no subsequent need to have an if (Minputstream!= null) judgment.   Solution: After Minputstream, no longer repeat the sentence after the null, will be later if the Minputstream change to Mdbuilder.   6, bug:should be a static inner class   BUG Description: This class is the inner class, but does not with its embedded Refe Rence to the object which created it.  Reference makes the instances of the class larger, and may keep the reference to the Creator object alive longer than NEC essary.  if possible, the class should be made static. (Static member classes are recommended instead for additional space and time overhead if you do not have access to non-static members of the perimeter class in the Member class.)   Problem Reason: The difference between non-static member classes and static member classes is that Non-static member classes are objects, and static member classes are classes. A non-static member class can access any member of the perimeter class, but only if the perimeter class object must exist. Java requires additional maintenance of the relationship between Non-static member classes and peripheral class objects. Parsing code private class Icctext and private class Mediametadata {No non-static members are accessed to the perimeter class, so FindBugs recommends that it be static.   WORKAROUND: Change these 2 inner classes to a static type.   7, Bug:switch statement found where one case falls through to the next case BUG Description: This method contains a Switch STA Tement where one case branch'll fall through to the next case. Usually you need the to-end this case with a or return. (a branch in a switch statement executes the next branch after execution.) Usually the case should be followed by a break or return statement to jump out.   Problem Reason: Case motionevent.action_up after execution did not break, will continue to walk case Motionevent.action_cancel branch. Parsing code logic, when the finger is raised, the lock screen icon needs to return to the original position, and the logic back to the original position is done in Action_cancel. That is, action_up logic also needs action_cancel logic inside.   Solution: Pull the logic out of the action_cancel into a function, action_up the logic and callThis function then do the break operation.   8, bug:unread field BUG Description: This field is never read.  consider removing it from the class. (The properties defined in the class have never been invoked and are recommended for deletion.)   Problem reason: defined in class member variable private hwviewproperty mcondition = null; only assignment operation mcondition = new Hwviewproperty (Mcontext, Value, Viewpropertytype.type_condition, mcallback); but there is no place to use this variable mcondition.   Solution: Remove mcondition Definition and assignment statement. Note, however, that mcondition = new Hwviewproperty (Mcontext,value, Viewpropertytype. Type_condition, Mcallback); Although the mcondition variable is not used later, the new Hwviewproperty object invokes the Hwviewproperty construction method when it actually does functional operation. Therefore, remove the mcondition, but need to keep the new Hwviewproperty (Mcontext,value, viewpropertytype.type_condition, Mcallback);   9, Bug:write to static field from instance method BUG Description: This instance method writes to a static field. This is tricky to get correct if multiple instances are being, and manipulated bad generally. (instance method writes a static variable directly.)   Problem Reason: Sinstance is a static member variable of a class, a non-static method Unregistercallbaks directly to it, a non-static method is associated with an object, and a problem may occur when multiple objects are assigned to the variable at the same time.   WORKAROUND: Use the Get and set methods when using static member variables。

FindBugs type of error and corresponding explanation third bomb

Recently, using FindBugs to analyze a project you've done recently, you'll find that your code has a lot of problems, and here's a little summary.

The following is the bug in my code combined with the network to do a bit of analytical learning, with the help of Google translation, the feeling of translation is still very awkward.

May expose internal representation by incorporating reference to mutable
Object. This is code stores a reference to a 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 security or

Other important properties,you'll need to do something different.
Storing a copy of the object is better approach in many situations.
The internal storage structure may be exposed because the reference can point to multiple objects.
This code causes a reference to an external multiple object to point to an internal object store address.
Security or other important attributes can be compromised if an instance is accessed by untrusted code or if an unchecked change occurs on multiple objects.
You need to do something different. Storing a copy of an object can be a better method in many cases.
Online Findbug use of the introduction of the article, wrote, click the following modify Findbug no bug tips,
Why do you want to put it in a temporary variable?      Java code public class Test {private string[] name;   Public string[] GetName () {string[] temp = name;   return temp;   Java code public void SetName (string[] name) {string[] temp = name;   THIS.name = temp; }   }

Because of the frequent occurrence of getter/setter in the code, I think this bug is not necessarily modified.

Dead Store to local variable
This instruction assigns a of local variable, but the "not" read or used in any subsequent

instruction. Often, this indicates a error, because the value computed is never used.
Note the Sun ' s Javac compiler often generates dead for the final local stores. Because FindBugs is

A bytecode-based tool, there is no easy way to eliminate this is false positives.
The local variable stores unused objects, which means that the variable is redundant.
Hashtable htable = new Hashtable ();
Object obj = new Object ();
obj = Htable.put ("uuid", "abcd1234");

Java code String ABC = "ABC";   String xyz = new String ("");   XYZ = ABC; System.out.println (XYZ);


Using Findbug to check out the dead store to the local variable error, which he means "native variables store unused objects"
Why does this happen? Because string xyz = new String ("");
This sentence performs 3 actions:
1) Create a reference xyz
2) Create a String object
3 Assigning a string reference to XYZ
Of these, the last two actions are superfluous, because you did not use the new string object in the subsequent program, but instead gave the XYZ a value.
XYZ = ABC; therefore, only string xyz = ABC is required; It's OK. In this way, findbugs will not be reported.

Write to static field from instance method
This instance method writes to a static field. This is tricky to get correct if multiple instances are

Being manipulated, and generally bad practice.
Writes values to the static field, such as: Java code private static Logger Logger;    Public Xxxactionctrl () {logger = Logger.getlogger (GetClass ()); Can be changed to: private static Logger Logger = Logger.getlogger (GetClass ());

Unread field:should This field to be static?
This class contains a instance the final field is initialized to a compile-time static value. Consider

Making the field static.
Unread field: This field should be static.
This class contains the last field of an instance initialized to a compile-time static value. Consider the static field. (FindBugs recommends modifying this property to be static).
Such as: Private final String Fail_flag = "Exit";
Instead: private static final String Fail_flag = "Exit";


Unread Field
This field is never read. Consider removing it from the class.
Unread fields (fields, properties)
A field that has never been used is declared in a class. Consider removing from the class.

Method concatenates strings using + in a loop
The method seems to is 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 leads to a

Cost quadratic in the number of iterations, as the growing string are recopied in each iteration.
Better performance can be obtained by using a stringbuffer (or StringBuilder in Java 1.5) explicitly.
string concatenation using methods in a loop +
The method seems to be built in loops using string concatenation. In each iteration, the string is converted to a stringbuffer/stringbuilder, appended to the

, and convert back to string. This can result in two iterations of the cost, because the growing string is replicated in each iteration.
Better performance, the use of StringBuffer (or StringBuilder) would be better.     Java code for example://The 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 ();

Inefficient use of keyset iterator instead of EntrySet iterator
This is accesses the value of a MAP entry, using a key that is retrieved from a keyset iterator. It is more efficient to use a iterator on the entryset of the "map" to avoid the Map.get (key) lookup.
Inefficient use, using keyset iterators instead of EntrySet iterators.
The use of EntrySet efficiency will be higher than keyset.
Keyset () can only fetch key through get () after iteration.
EntrySet () iteration can be E.getkey (), E.getvalue () takes key and value, and returns the entry interface.

Field isn ' t final but should be.
A mutable static field could is changed by malicious code or by accident from another package. The field

Could be made the final to avoid this vulnerability.
The field should be declared final, but in fact it is not declared final.
A variable static field can be changed by malicious code, using the final keyword to avoid this vulnerability.

Call to Equals () with null argument.
This method calls Equals (Object), passing a null value as the argument. According to the contract of the Equals () method, which is should always return false.
Use the null parameter to call Equals ().
This method call Equals (object) and passes a null value as a parameter. Depending on the Equals () method of the contract, this call should always return false.
such as: Querystr.equals (NULL); This use is not advisable, although it can be compiled.

Invocation of toString on an array.
The code invokes toString on an array, which'll generate a fairly useless result such as [c@16f0472.

Consider using arrays.tostring to convert the array into a readable String that gives the contents of the array. Programming Puzzlers, Chapter 3, Puzzle 12.
The log group calls the ToString () method.
When the code calls the ToString () method on the array, it produces a rather useless shape like [c@16f0472 result. Consider using the Arrays.tostring method

Converts an array to a readable string that gives the contents of a group.
For example: In the use of System.out.println (Xx.readnext ()), you will encounter such a hint, Readnext () method put back to a string[].
Could read:
string[] arr = Reader.readnext ();
System.out.println (Arrays.aslist (arr). toString ());
(It seems to be a bit of trouble, never thought of a more concise approach).


Nullcheck of value previously dereferenced
A value is checked-to-whether it is null, but this value can ' t being null because it was previously

Dereferenced and if it were null a null pointer exception would have at the occurred earlier.

Essentially, this code and the previous dereference disagree as to whether this value are allowed to be

Null. Either the check is redundant or the previous dereference is erroneous.
Null value checks are discarded before this code.
A value is selected here to see if it is empty, but this value cannot be empty because it discards the null value check before, and if it is NULL, the null pointer is different

Will often occur here, if it is empty an empty pointer exception will occur earlier dereference.
In essence, this code and the preceding discarded null value check will appear inconsistent, whether this value is allowed
Empty.
There are two situations in which the bug occurs: An extra null check, and an obsolete null value check at the front.
For example: We often use this actionform,
String Clazzid = Request.getparameter ("Clazzid");//SCRIPT1
Studentform.setclazzid (Clazzid);//Script2
This error tends to occur in script2 because the SCRIPT1 does not check if the Clazzid is null.
Modified to:
if (Clazzid!= null) {
Studentform.setclazzid (Clazzid);
}

Determines whether a clazzid is null before it is set to use.

Possible null pointer dereference on exception path
A reference value which is null in some exception control path is dereferenced here.  This may leads to a nullpointerexception when the code is executed. The note is because FindBugs currently does not prune infeasible the exception paths, this May is a false warning.
Also Note This FindBugs considers the default case of "a" switch statement to is a exception path, since the default case I s often infeasible.
Discarding a null value check in the exception section may cause a null pointer exception to appear in the following code.   such as: Java code MD = NULL;      try {md = messagedigest.getinstance ("SHA-256");     Md.update (BT); catch (NoSuchAlgorithmException e) {e.printstacktrace ();//SCRIPT1} byte[] Digest = Md.digest ();//Script 2 bugs appear in the Script2 place, at Script1 Place to deal with the corresponding exception can be, such as throw or return;

Possible NULL pointer dereference
There is a branch of statement to, if executed, guarantees that a null value would be dereferenced, which would generate A nullpointerexception when the code is executed. Of course, the problem might being that branch or statement are infeasible and that the null pointer exception can ' t ever be executed; Deciding is beyond the ability of FindBugs.
A possible null pointer reference.
As in JDBC programming, this bug is often present when the resultset is closed (Rs.close ()), and the solution is easy to think about whether it is null or

Use try...catch...finally.

Call to Equals () comparing different types
This method calls Equals (Object) on two references of the different class types with no common subclasses.

Therefore, the objects being compared are unlikely the same class at runtime (unless some

Application classes were not analyzed, or dynamic class loading can occur at runtime). According to the

Contract of Equals (), objects of different classes should always as compare; Therefore, according

To the contract defined by Java.lang.Object.equals (Object), the result of this comparison would always be

False at runtime.
Call Equals () to compare different types.
This method invokes a reference that is equivalent to two different class types and does not have a common subclass (object).
Therefore, the object being compared is a class member that is less likely to be the same at run time (unless some
The application class does not parse or dynamic class loading can occur at run time. According
Equals () The rules of not homogeneous objects should always be more unequal, therefore, according to
Contract (object) defined by Java.lang.Object.equals, false will always be the result of comparison
Error at run time.

。。。

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.