FindBugs规则整理 中文版

合集下载

FindBugs帮助文档

FindBugs帮助文档

Product name产品名称Confidentiality level密级FindBugs帮助文档内部公开Product version产品版本Total 29 pages 共29页V1.0FindBugs帮助文档(软件工程部)Prepared by拟制邓爱平36829Date日期2008-10-16Reviewed by 审核人Date 日期Reviewed by 审核人Date 日期Authorized by批准Date日期Huawei Technologies Co., Ltd.华为技术有限公司All rights reserved版权所有侵权必究文档版本 1.1 (2006-03-01) 华为技术有限公司1-1文档版本 1.1 (2006-03-01) 华为技术有限公司1-2修订记录日期文档版本产品版本描述作者2008-10-16 1.0 初稿邓爱平36829文档版本 1.1 (2006-03-01) 华为技术有限公司1-3目录(Contents)1 目的和范围................................................................................................................................... 1-61.1 目的 .............................................................................................................................................. 1-61.2 范围 .............................................................................................................................................. 1-62 FindBugs使用 .............................................................................................................................. 2-62.1 FindBugs简介................................................................................................................................ 2-62.1.1 FindBugs能解决的问题......................................................................................................... 2-62.1.2 同类产品介绍 ....................................................................................................................... 2-92.2 如何安装FindBugs ........................................................................................................................ 2-92.2.1 图形界面/命令行................................................................................................................... 2-92.2.2 安装Eclipse插件................................................................................................................... 2-92.3 如何使用FindBugs ...................................................................................................................... 2-122.3.1 在图形界面下使用FindBugs(JDK1.5上进行)...................................................................... 2-122.3.2 在命令行下使用FindBugs .................................................................................................. 2-152.3.3 在Eclipse下使用FindBugs .................................................................................................. 2-172.3.4 通过ant任务脚本使用FindBugs .......................................................................................... 2-202.4 FindBugs的高级功能................................................................................................................... 2-222.4.1 规则配置............................................................................................................................. 2-222.4.2 使用过滤器......................................................................................................................... 2-222.4.3 FindBugs的局限性.............................................................................................................. 2-232.4.4 FindBugs推行细则.............................................................................................................. 2-243 常见问题FAQ及其解答............................................................................................................ 3-243.1 在Eclipse下在更改了检查出的错误后,为什么无法实时刷新检查结果 ...................................... 3-243.2 在Eclipse下使用FindBugs时,如何将发现的问题显示在Problems视图中................................. 3-243.3 为什么Eclipse插件加载不成功.................................................................................................... 3-253.4 如何配置FindBugs的通过准则.................................................................................................... 3-253.5 为什么在图形界面下使用FindBugs时,关联不到源代码............................................................ 3-253.6 文档胶片中说到的FindBugs帮助文档在什么地方....................................................................... 3-263.7 到什么地方获取FindBugs相关资料............................................................................................. 3-263.8 对于不修改的Bug,怎么给出原因说明....................................................................................... 3-263.9 Findbugs占用大量内存,而且运行时间很长,应该如何缩短运行时间.................................... 3-27文档版本 1.1 (2006-03-01) 华为技术有限公司1-43.10 每个工程目录下的.fbprefs 文件有何作用................................................................................. 3-273.11 Bug Explorer窗口的export有何功能 .......................................................................................... 3-283.12 如何了解findbugs提供的每个规则的含义 ................................................................................. 3-284 参考引用..................................................................................................................................... 4-28文档版本 1.1 (2006-03-01) 华为技术有限公司1-51 目的和范围1.1 目的FindBugs 是一个代码静态分析工具,它检查类或者JAR 文件,将字节码与一组缺陷模式进行对比以发现可能的问题。

FindBugs介绍.

FindBugs介绍.

附:效果
附:效果
自定义检查器
18 19 20 21 22 23
示例
public void visit(Code code) { seenGuardClauseAt = Integer.MIN_VALUE; logBlockStart = 0; logBlockEnd = 0; super.visit(code); }
应判断inputread的返回值实际读入多少字节未检查返回值返回值被丢弃stringreplace示例续构造器constructor使用未初始化变量jbosspublicbytearraycallbackstringpropmpt一概要二使用三缺陷模式四实现技术五自定义检测器访问者visitor模式字节码抽象语法树使用bcelbytecodeengineeringlibrary操作字节码也支持asm字节码操作库遍历抽象语法树
使用(续)
三 Eclipse插件
目录
一 概要 二 使用 三 缺陷模式
四 实现技术 五 自定义检测器
缺陷模式
缺陷模式
经常出现的缺陷的表现样式 分类
单线程 多线程同步 性能 安全性、健壮性
缺陷模式
equals(Object)变体
equals(Foo)
示例
应重载父类:Foo.equals(Object)
自定义检查器
32
示例
if (seen == IFEQ && (PC >= seenGuardClauseAt + 3 && PC < seenGuardClauseAt + 7)) { 33 logBlockStart = branchFallThrough; 34 logBlockEnd = branchTarget; 35 }

FindBugs规则整编中文版

FindBugs规则整编中文版
27.
28.
29.
30.
Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)
This class defines an enumeration, and equality on enumerations are defined using object identity. Defining a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don't do it.
In rare cases, people do define nonsymmetrical equals methods and still manage to make their code work. Although none of the APIs document or guarantee it, it is typically the case that if you check if a Collection<String> contains a Foo, the equals method of argument (e.g., the equals method of the Foo class) used to perform the equality checks.

FindBugs使用手册

FindBugs使用手册

文件编号:配置项编号:FindBugs使用手册文档版本号V1.0农信银资金清算中心创新研发部文档修订记录编号章节名称修订内容简述修订日期版本号修订人批准人1创建《FindBugs使用手册》2011-07-12V1.0李远卓FindBugs使用手册目录1、FindBugs简介 (4)2、FindBugs的检查规则 (4)2.1Correctness(正确性) (4)2.2Bad practice(不良实践) (5)2.3Performance(性能) (5)2.4Multithreaded correctness(多线程正确性) (6)2.5Dodgy(不可靠) (7)3、FindBugs使用 (8)3.1安装FindBugs (8)3.2配置FindBugs (8)3.3使用FindBugs (8)FindBugs使用手册1、FindBugs简介FindBugs是用于java代码检查的一种静态分析工具,它检查类或者JAR文件,将字节码与一组缺陷模式进行对比以发现可能的问题。

有了静态分析工具,就可以在不实际运行程序的情况对软件进行分析。

FindBugs专注于找出潜在程序错误,而不是编码风格问题,目的在于提高程序的健壮性。

2、FindBugs的检查规则FindBugs提出了超过200种规则,这些规则可主要分为如下类别:2.1Correctness(正确性)这些问题涉及到可能在某些方面不正确的代码。

如:代码有无限递归,或者读取为写入的字段,这类问题几乎无疑是程序的错误。

例1:使用未初始化的类成员,可能导致NullPointException代码:public class FindBugsTest{private List items;public void addItem(String item){items.add(item);}}FindBugs检测结果:Bug:Read of unwritten field itemsPattern id:NP_UNWRITTEN_FIELD,type:NP,category:CORRECTNESSThe program is dereferencing a field that does not seem to ever have a non-null value written to it.Dereferencing this value will generate a null pointer exception.例2:不使用方法的返回值代码:String aString="bob";aString.replace('b','p');FindBugs检测结果:Bug:com.nxy.test.FindBugsTest.testString()ignores return value of String.replace(char,char)Pattern id:RV_RETURN_VALUE_IGNORED,type:RV,category:CORRECTNESSFindBugs使用手册The return value of this method should be checked.One common causeof this warning is to invoke a method on an immutable object,thinking that it updates the object.For example,in the followingcode fragment,String dateString=getHeaderField(name);dateString.trim();the programmer seems to be thinking that the trim()method willupdate the String referenced by dateString.But since Strings are immutable,the trim()function returns a new String value,which isbeing ignored here.The code should be corrected to:String dateString=getHeaderField(name);dateString=dateString.trim();2.2Bad practice(不良实践)这类问题明确违反建议的编程标准。

Findbug代码规范_分享

Findbug代码规范_分享

Findbug代码规范坏的编程实践HE类定义了equals(),却没有hashCode();类定义了equals(),却使用Object. hashCode();类定义了hashCode(),却没有equals();类定义了hashCode(),却使用Object.equals();类继承了equals(),却使用Object.hashCode()。

重写equals()必须重写hashCode()DE,异常无终止或不处理异常一般情况下,异常应该被处理或报告,或被方法抛出。

Correctness有潜在问题的情况NP, 空指针被引用方法没有检查参数是否null;null值产生并被引用;传给方法一个声明为@NonNull的null参数;方法的返回值声明为@NonNull实际是null。

对readline()的直接引用,而没有判断是否null;对方法调用的直接引用,而方法可能返回nullNm类名不规范,不以大写字母开头;SQL方法尝试访问一个Prepared Statement无效的列索引; 方法尝试访问一个ResultSet对象无效的索引;PreparedStatement pstmt = con.prepareStatement("UPDATE table4 SET m = ? WHERE x = ?"); UwFUnwritten field: com.mobogenie.util.InstallUtil.pkg变量pkg一直没有被用到。

初始化的变量属性置成null,这样所有的读取都是null,这样这个属性是否有必要存在;Malicious code vulnerability可能受到的恶意攻击FI一个类的finalize()应该是protected,而不是public的。

finalize() 方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。

MS属性是可变的数组;属性是可变的Hashtable;属性应该是protected的;public static int mTypeCode = 0; Multithreaded correctness多线程的使用ESync:空的同步块,很难被正确使用。

Findbugs缺陷等级对照表

Findbugs缺陷等级对照表

FindBugs Bug DescriptionsThis document lists the standard bug patterns reported by version 0.8.5.SummaryDescriptionsAM: Creates an empty jarThe code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty Jar. The contents of the entry should be written to the Jar the calls to putNextEntry() andcloseEntry().AM: Creates an empty zipThe code calls putNextEntry(), immediately followed by a call to closeEntry(). This results in an empty Zip. The contents of the entry should be written to the Zip the calls to putNextEntry() andcloseEntry().BIT: Incompatible bit masksThis method compares an expression of the form (a & C) to D, which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.BIT: Incompatible bit masksThis method compares an expression of the form (a & 0) to 0, which will always compare equal. This may indicate a logic error or typo.BIT: Incompatible bit masksThis method compares an expression of the form (a | C) to D. which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.Typically, this bug occurs because the code wants to perform a membership test in a bit set, but uses the bitwise OR operator ("|") instead of bitwise AND ("&").BOA: Class overrides a method implemented in super class Adapter wronglyThis method overrides a method found in a parent class, where that class is an Adapter that implements a listener defined in thejava.awt.event or javax.swing.event package. As a result, this method will not get called when the event occurs.BRSA: Method attempts to access a result set field with index 0A call to getXXX or updateXXX methods of a result set was made where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.CN: Class implements Cloneable but does not define or use clone methodClass implements Cloneable but does not define or use the clone method.CN: clone method does not call super.clone()This class defines a clone() method that does not call super.clone(), and is not final. If this class ("A") is extended by a subclass ("B"), and the subclass B calls super.clone(), then it is likely that B's clone() method will return an object of type A, which violates the standard contract for clone().If all clone() methods call super.clone(), then they are guaranteedto use Object.clone(), which always returns an object of the correct type.Co: Covariant compareTo() method definedThis class defines a covariant version of compareTo(). To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type ng.Object.DE: Method might drop exceptionThis method might drop an exception. In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.DE: Method might ignore exceptionThis method might ignore an exception. In general, exceptions should be handled or reported in some way, or they should be thrownout of the method.Dm: Method invokes System.exit(...)Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.EC: Call to equals() with null argumentThis method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return false.EC: Call to equals() comparing different interface typesThis method calls equals(Object) on two references of unrelated interface types (neither is a subtype of the other). According to the contract of equals(), objects of different classes should always compare as unequal. Note that it is possible that the program contains classes that implement both interfaces, so the comparison may be valid. However, it is worth inspecting closely.EC: Call to equals() comparing different typesThis method calls equals(Object) on two references of different types. According to the contract of equals(), objects of different classes should always compare as unequal; therefore, it is likelythat the result of this comparision will always be false at runtime.ES: Comparison of String objects using == or !=This code compares ng.String objects for reference equalityusing the == or != operators. Unless both strings are either constants in a source file, or have been interned using theString.intern() method, the same string value may be represented by two different String objects. Consider using the equals(Object) method instead.Eq: Covariant equals() method definedThis class defines a covariant version of equals(). To correctly override the equals() method in ng.Object, the parameter ofequals() must have type ng.Object.Eq: Covariant equals() method defined, Object.equals(Object) inheritedThis class defines a covariant version of the equals() method, but calls the normal equals(Object) method defined in the baseng.Object class. The class should probably define a non-covariant version of equals(). (I.e., a method with the signature boolean equals(ng.Object).FI: Explicit invocation of finalizerThis method contains an explicit invocation of the finalize() method on an object. Because finalizer methods are supposed to be executed once, and only by the VM, this is a bad idea.FI: Finalizer does not call superclass finalizerThis finalize() method does not make a call to its superclass'sfinalize() method. So, any finalizer actions defined for the superclass will not be performed. Add a call to super.finalize(). FI: Finalizer nullifies superclass finalizerThis empty finalize() method explicitly negates the effect of any finalizer defined by its superclass. Any finalizer actions defined for the superclass will not be performed. Unless this is intended, delete this method.HE: Class defines equals() but not hashCode()This class overrides equals(Object), but does not overridehashCode(). Therefore, the class may violate the invariant thatequal objects must have equal hashcodes.HE: Class defines equals() and uses Object.hashCode()This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from ng.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.If you don't want to define a hashCode method, and/or don't believe the object will ever be put into a HashMap/Hashtable, define thehashCode() method to throw UnsupportedOperationException.HE: Class defines hashCode() but not equals()This class defines a hashCode() method but not an equals()method. Therefore, the class may violate the invariant that equal objects must have equal hashcodes.HE: Class defines hashCode() and uses Object.equals()This class defines a hashCode() method but inherits its equals() method from ng.Object (which defines equality by comparing object references). Although this will probably satisfy the contract that equal objects must have equal hashcodes, it is probably not what was intended by overriding the hashCode() method. (Overriding hashCode() implies that the object's identity is based on criteria more complicated than simple reference equality.)HE: Class inherits equals() and uses Object.hashCode()This class inherits equals(Object) from an abstract superclass, and hashCode() from from ng.Object (which returns the identity hash code, an arbitrary value assigned to the object by theVM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.If you don't want to define a hashCode method, and/or don't believe the object will ever be put into a HashMap/Hashtable, define the hashCode() method to throw UnsupportedOperationException.IC: Initialization circularityA circularity was detected in the static initializers of the two classes referenced by the bug instance. Many kinds of unexpected behavior may arise from such circularity.IJU: TestCase implements setUp but doesn't call super.setUp()Class is a JUnit TestCase and implements the setUp method. The setUp method should call super.setUp(), but doesn't.IMSE: Dubious catching of IllegalMonitorStateExceptionIllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you donot hold a lock on).It: Iterator next() method can't throw NoSuchElement exceptionThis class implements the java.util.Iterator interface. However, its next() method is not capable of throwingjava.util.NoSuchElementException. The next() method should be changed so it throws NoSuchElementException if is called when there are no more elements to return.MF: Class defines field that obscures a superclass fieldThis class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.MF: Method defines a variable that obscures a fieldThis method defines a local variable with the same name as a field in this class or a superclass. This may cause the method to read an uninitialized value from the field, leave the field uninitialized, or both.MWN: Mismatched notify()This method calls Object.notify() or Object.notifyAll() without obviously holding a lock on the object. Calling notify() ornotifyAll() without a lock held will result in an IllegalMonitorStateException being thrown.MWN: Mismatched wait()This method calls Object.wait() without obviously holding a lock on the object. Calling wait() without a lock held will result in an IllegalMonitorStateException being thrown.NP: Null pointer dereference in methodA null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed.NP: Null pointer dereference in method on exception pathA pointer which is null on an exception path is dereferencedhere. This will lead to a NullPointerException when the code is executed. Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.NP: Possible null pointer dereference in methodA reference value dereferenced here might be null at runtime. This may lead to a NullPointerException when the code is executed.NP: Possible null pointer dereference in method on exception pathA reference value which is null on some exception control path is dereferenced here. This may lead to a NullPointerException when the code is executed. Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.NS: Questionable use of non-short-circuit logicThis code seems to be using non-short-circuit logic (e.g., & or |) rather than short-circuit logic (&& or ||). Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error.Nm: Class defines equal(); should it be equals()?This class defines a method equal(Object). This method does not override the equals(Object) method in ng.Object, which is probably what was intended.Nm: Confusing method namesThe referenced methods have names that differ only by capitalization.Nm: Confusing method nameThis method has the same name as the superclass of the class it is defined in.Nm: Class defines hashcode(); should it be hashCode()?This class defines a method called hashcode(). This method does not override the hashCode() method in ng.Object, which is probably what was intended.Nm: Class defines tostring(); should it be toString()?This class defines a method called tostring(). This method does not override the toString() method in ng.Object, which is probably what was intended.Nm: Very confusing method namesThe referenced methods have names that differ only by capitalization.ODR: Method may fail to close database resourceThe method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.ODR: Method may fail to close database resource on exceptionThe method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all exception paths out of the method. Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.OS: Method may fail to close streamThe method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appearto close the stream on all paths out of the method. This may result in a leak. It is generally a good idea to use a finally block to ensure that streams are closed.OS: Method may fail to close stream on exceptionThe method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appearto close it on all possible exception paths out of the method. This may result in a leak. It is generally a good idea to use a finally block to ensure that streams are closed.PZLA: Consider returning a zero length array rather than nullIt is often a better design to return a length zero array rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.On the otherhand, using null to indicate "there is no answer to this question", then it is probably appropriate. For example, () returns an empty list if given a directory containing no files, and returns null if the not a directory.RC: Suspicious reference comparisonThis method compares two reference values using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. Examples of classes which should generally not be compared by reference are ng.Integer,ng.Float, etc.RCN: Redundant comparision to null of previously checked valueThis method contains a redundant comparison of a reference value to null. Two types of redundant comparison are reported:•Both values compared are definitely null•One value is definitely null and the other is definitely not nullThis particular warning generally indicates that a value known not to be null was checked against null. While the check is not necessary,it may simply be a case of defensive programming.RCN: Redundant comparison to nullThis method contains a redundant comparison of a reference value to null. Two types of redundant comparison are reported:•Both values compared are definitely null•One value is definitely null and the other is definitely not nullThis particular warning represents two specific kinds of redundant comparisions:1. A value was dereferenced, and later explicitly compared tonull: this often indicates an error in the method2. A literal null value was explicitly compared to null: this mayindicate that the method was modified without completeunderstanding of the invariants of the methodRR: Method ignores results of InputStream.read()This method ignores the return value of one of the variants ofjava.io.InputStream.read() which can return multiple bytes. If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were read than the caller requested. This is a particularly insidious kind of bug, because in many programs, reads from input streams usually do read the full amount of data requested, causing the program to fail only sporadically.RR: Method ignores results of InputStream.skip()This method ignores the return value of java.io.InputStream.skip() which can skip multiple bytes. If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were skipped than the caller requested. This is aparticularly insidious kind of bug, because in many programs, skips from input streams usually do skip the full amount of data requested, causing the program to fail only sporadically. With Buffered streams, however, skip() will only skip data in the buffer, and will routinely fail to skip the requested number of bytes.RV: Method ignores return valueThe return value of this method should be checked.SA: Self assignment of fieldThis method contains a self assignment of a field; e.g.int x;public void foo() {x = x;}Such assignments are useless, and may indicate a logic error or typo.SI: Static initializer for class creates instance before all static final fields assignedThe class's static initializer creates an instance of the classbefore all of the static final fields are assigned.SIO: Unnecessary type check done using instanceof operatorType check performed using the instanceof operator where it can be statically determined whether the object is of the type requested.SW: Certain swing methods should only be invoked from the Swing event thread(From JDC Tech Tip): The Swing methods show(), setVisible(), andpack() will create the associated peer for the frame. With the creation of the peer, the system creates the event dispatch thread. This makes things problematic because the event dispatch thread could be notifying listeners while pack and validate are still processing. This situation could result in two threads going through the Swing component-based GUI -- it's a serious flaw that could result in deadlocks or other related threading issues. A pack call causes components to be realized. As they are being realized (that is, not necessarily visible), they could trigger listener notification on the event dispatch thread.Se: Non-transient non-serializable instance field in serializable classThis Serializable class defines a non-primitive instance field whichis neither transient, Serializable, or ng.Object, and does not appear to implement the Externalizable interface or the readObject() and writeObject() methods. Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field.Se: serialVersionUID isn't finalThis class defines a serialVersionUID field that is not final. The field should be made final if it is intended to specify the version UID for purposes of serialization.Se: serialVersionUID isn't longThis class defines a serialVersionUID field that is not long. Thefield should be made long if it is intended to specify the version UID for purposes of serialization.Se: serialVersionUID isn't staticThis class defines a serialVersionUID field that is not static. The field should be made static if it is intended to specify the version UID for purposes of serialization.Se: Class is Serializable but its superclass doesn't define a void constructorThis class implements the Serializable interface and its superclass does not. When such an object is deserialized, the fields of the superclass need to be initialized by invoking the void constructor of the superclass. Since the superclass does not have one, serialization and deserialization will fail at runtime.Se: Class is Externalizable but doesn't define a void constructorThis class implements the Externalizable interface, but does not define a void constructor. When Externalizable objects are deserialized, they first need to be constructed by invoking the void constructor. Since this class does not have one, serialization and deserialization will fail at runtime.SnVI: Class is Serializable, but doesn't define serialVersionUIDThis class implements the Serializable interface, but does not define a serialVersionUID field. A change as simple as adding a reference toa .class object will add synthetic fields to the class, which will unfortunately change the implicit serialVersionUID (e.g., adding a reference to String.class will generate a static fieldclass$java$lang$String). Also, different source code to bytecode compilers may use different naming conventions for synthetic variables generated for references to class objects or inner classes. To ensure interoperability of Serializable across versions, consider adding an explicit serialVersionUID.UCF: Useless control flow in methodThis method contains a useless control flow statement. Often, this is caused by inadvertently using an empty statement as the body of an if statement, e.g.:if (argv.length == 1);System.out.println("Hello, " + argv[0]);UI: Usage of GetResource may be unsafe if class is extendedCalling this.getClass().getResource(...) could give results other than expected if this class is extended by a class in another package.UR: Uninitialized read of field in constructorThis constructor reads a field which has not yet been assigned a value. This is often caused when the programmer mistakenly uses the field instead of one of the constructor's parameters.UwF: Unwritten fieldThis field is never written. All reads of it will return thedefault value. Check for errors (should it have been initialized?), or remove it if it is useless.EI: Method may expose internal representation by returning reference to mutable objectReturning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of theobject. 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. Returning a new copy of the object is better approach in many situations.FI: Finalizer should be protected, not publicA class's finalize() method should have protected access, not public.MS: Method may expose internal static state by storing a mutable object into a static fieldThis code stores a reference to an externally mutable object into a static field. If 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.MS: Field isn't final and can't be protected from malicious codeA mutable static field could be changed by malicious code or by accident from another package. Unfortunately, the way the field is used doesn't allow any easy fix to this problem.MS: Public static method may expose internal representation by returning arrayA public static method returns a reference to an array that is part of the static state of the class. Any code that calls this method can freely modify the underlying array. One fix is to return a copy of the array.MS: Field should be both final and package protectedA mutable static field could be changed by malicious code or by accident from another package. The field could be made package protected and/or made final to avoid this vulnerability.MS: Field is a mutable arrayA final static field references an array and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the array.MS: Field is a mutable HashtableA final static field references a Hashtable and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the Hashtable.MS: Field should be moved out of an interface and made package protectedA final static field that is defined in an interface references a mutable object such as an array or hashtable. This mutable object could be changed by malicious code or by accident from another package. To solve this, the field needs to be moved to a class and made package protected to avoid this vulnerability.MS: Field should be package protectedA mutable static field could be changed by malicious code or by accident. The field could be made package protected to avoid this vulnerability.MS: Field isn't final but should beA mutable static field could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability.2LW: Wait with two locks heldWaiting on a monitor while two locks are held may causedeadlock. Performing a wait only releases the lock on the object being waited on, not any other locks. This not necessarily a bug, but is worth examining closely.DC: Possible double check of fieldThis method may contain an instance of double-checked locking. This idiom is not correct according to the semantics of the Java memory model. For more information, see the web page .IS2: Inconsistent synchronizationThe fields of this class appear to be accessed inconsistently with respect to synchronization. This bug report indicates that the bug pattern detector judged that1.The class contains a mix of locked and unlocked accesses,2.At least one locked access was performed by one of the class'sown methods, and3.The number of unsynchronized field accesses (reads and writes)was no more than one third of all accesses, with writes beingweighed twice as high as readsA typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.You can select the nodes labeled "Unsynchronized access" to show the code locations where the detector believed that a field was accessed without synchronization.Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.This description refers to the "IS2" version of the pattern detector, which has more accurate ways of detecting locked vs. unlocked accesses than the older "IS" detector.LI: Incorrect lazy initialization of static fieldThis method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site.ML: Method synchronizes on an updated fieldThis method synchronizes on an object references from a mutable field. This is unlikely to have useful semantics, since different threads may be synchronizing on different objects.NN: Naked notify in methodA call to notify() or notifyAll() was made without any (apparent) accompanying modification to mutable object state. In general, calling a notify method on a monitor is done because some condition another thread is waiting for has become true. However, for the condition to be meaningful, it must involve a heap object that is visible to both threads.This bug does not necessarily indicate an error, since the change to。

findbugs常见Bug以及处理办法[1]

findbugs常见Bug以及处理办法[1]

FindBugs实践1、Bug级别根据Bug可能导致的后果,FindBugs定义了若干Bug级别,主要的级别如下所示:Bad Practice: 不好的实践Correctness: 正确性Experimental Internationalization:Malicious code vulnerability: 存在漏洞的有害代码Multithreaded correctness: 多线程正确性Performance:性能Security:安全Dodgy: 欺骗性代码2、常见Bug以及处理办法a)不需要处理May expose internal representation by incorporating reference to mutable object描述:调用set方法,修改对象属性,被修改的对象属性是一个可变的对象;May expose internal representation by returning reference to mutable object描述:调用get方法,获得对象属性,获得的对象属性是一个可变的对象;b)建议处理Dead store to local variable描述:对一个局部变量赋值,但是这个局部变量可能不会被用到;处理方式:确认此局部变量是否会被使用,如果确实不会被用到,请去掉;Exception is caught when Exception is not thrown描述:调用的方法中不会抛出异常,但是调用方法的时候尝试使用try catch 捕获异常;处理方式:确认此方法的调用会不会导致异常的发生,如果不会抛出异常请去掉try catch,确认方法调用会不会抛出异常关键是对方法调用参数的合法性进行检查,排除调用这个方法时可能抛出异常的参数;Unread field描述:某个对象的属性不会被读取处理方式:确认此局部变量是否会被使用,如果确实不会被用到,请去掉,和Dead store to local variable一样处理,只是这里针对的是不是局部变量;Call to static DateFormat描述:调用静态的DateFormat对象处理方式:DateFormat对象是线程不安全的,建议不要使用静态的DateFormat,但是DateFormat不会被修改的话,也可以不用修改;Class is Serializable, but doesn't define serialVersionUID描述:类是可序列化的,但是没有定义serialVersionUID;处理方式:自动生成serialVersionUID;Field only ever set to null描述:Field一直被设置为null;处理方式:检查相关filed的调用情况,看所有对Field的操作是否都是将Field设置为null;Usage of GetResource may be unsafe if class is extended描述:如果一个类被继承了,使用getResource可能会不安全处理方式:Unsynchronized get method, synchronized set method描述:非同步的get方法,同步的set方法处理方式:修改为一致的情况Unconditional wait描述:无条件的wait处理方式:Switch statement found where one case falls through to the next case描述:switch语句中有case没有使用break;处理方式:增加break;Should be a static inner class描述:应该是静态内部类;处理方式:增加static修饰符使其成为静态内部类;Private method is never called描述:私有方法没有被调用;处理方式:考虑将其注释掉;c)必须处理Method invokes toString() method on a String描述:对String对象调用toString方法;处理方式:确认此局部变量是否会被使用,如果确实不会被用到,请去掉;Inefficient use of keySet iterator instead of entrySet iterator描述:在遍历Collection对象的时候,使用entrySet的性能会比keySet性能高;处理方式:使用迭代器迭代Collection的时候,优先使用entrySet;Load of known null value描述:对已知为null的对象进行一些操作,例如if(ids ==null && ids.length<=0);已知ids为空了,但是还调用ids.length属性,应该将&&修改为||;处理方式:这种情况很多时候都是出现在上面的示例代码中,请检查&&和|| 的使用;Method invokes inefficient Number constructor; use static valueOf instead描述:调用Number对象(Long, Integer, Float)低效的构造方法,使用静态的valueOf方法;处理方式:在将一个String对象转化为对应的Number对象的时候,通常会使用new Long(stringObj);实际上使用Long.valueOf(stringObj)会更好;Null pointer dereference描述:对已知为null的对象进行一些操作,例如if(ids ==null && ids.length<=0);已知ids为空了,但是还调用ids.length属性,应该将&&修改为||;处理方式:这种情况很多时候都是出现在上面的示例代码中,请检查&&和|| 的使用;和Load of known null value相伴出现,处理方式一样;Equals method should not assume anything about the type of its argument描述:Equals方法不应该对类型作任何假设;处理方式:通常在调用Class.isInstance去判断对象的相等性的时候会出现;Field isn't final but should be描述:某些字段应该是final的,但是不是;处理方式:public static String LOCAL_CACHE_PROPERTY_NAME = "cache.clustering.local.class"; 通常会出现在静态常量的定义中;Write to static field from instance method描述:在实例方法中修改静态属性;处理方式:避免在实例方法中对静态变量做修改;Unused field描述:未被用到的字段;处理方式:去掉如果确实没有用到;Nullcheck of value previously dereferenced描述:先前已经进行过空值检查了;处理方式:在这里不需要进行空置检查;Method uses the same code for two branches描述:if else 两个分支执行同样的代码;处理方式:检查代码是否正确,如果是正确的,就不需要if else了;Method might ignore exception描述:方法可能忽略异常处理方式:对异常的处理作出检查,这样的情况通常出现在如下代码:Try{ }catch(Exception r){ }。

findbugs bug描述的中英文对照

findbugs bug描述的中英文对照

错误关键字关注点Bad practice不好的习惯Correctness代码的正确性Dodgy小问题Malicious code vulnerability恶意代码Internationalization 国际化问题Performance性能问题Security安全性问题Multithreaded currectness线程问题Experrimental实验性问题Bug id(s)Speed NP fastJCIP fastCN fastSE fastDP fastIMSE fastNm fastDE fastAM moderateEq fastFI fastJ2EE fastOS|ODR fastUI fastISC fastIt fastRR fast ES|RC|EC slowBIT fast RV fastNm fast Eq|Co|HE fast NP|RCN slow Eq fastNP|RV|Dm|SW|Bx|DMI|BIT|INT|BC fast SnVI|Se|WS|RS fast DLS|EC|BSHIFT|DMI|IM|IC|ICAST|Bx|IJU fast SI|IC fastFI fast IO fast SQL fastRE fast BOA fast TQ slow SA fast MF fast NP slowSA fastSA fastUR fastGC|DMI fastNP fastIL fastIL fastIL slowIJU fast QBA fast RpC fast SIO fastSTI fast UMAC fastVA fastBC|NP fastDLS|IP moderate FE fast UCF fastFS fastICAST fastSF fastST|NP|Uwf|SS|UuF|UrF|SIC fastRV fastDm fastCI fastIA moderate DB fastQF fastSA fast DMI fastNS fastNP fast MTIA fast PZLA fastRI fast REC fast XFB fast OBL slowMS|EI|EI2fastMS fastDC fast ESync fastIS|MSF slow JLM moderateMWN moderate NN fastRu fast SWL slowSP fast TLW slowUW fastUL moderate UG fastLI moderate ML fastSC fast STCAL fastNP moderate WL fastML fastVO fastWa|No fast UPM fast HSC fastITA fastBx fast SBSC fastDm fastUM fast WMI fast HRS|XSS fast SQL moderate Dm|DMI fastCategory Bad practice Bad practiceBad practice Bad practice Bad practice Bad practice Bad practice Bad practiceBad practice Bad practice Bad practice Bad practiceBad practice Bad practice Bad practice Bad practiceBad practiceBad practice|CorrectnessBad practice|CorrectnessBad practice|CorrectnessBad practice|Correctness Bad practice|Correctness|Dodgy Bad practice|Correctness|Dodgy Bad practice|Correctness|Dodgyectness|Dodgy|Internationalization|Multithreaded currec Bad practice|Correctness|Dodgy|Multithreaded currectnesBad practice|Correctness|Dodgy|PerformanceBad practice|DodgyBad practice|Malicious code vulnerabilityCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectnessCorrectness Correctness|DodgyCorrectness|Dodgy Correctness|Dodgy Correctness|DodgyCorrectness|DodgyCorrectness|DodgyCorrectness|Dodgy Correctness|Dodgy|PerformanceDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyDodgyExperrimental Malicious code vulnerability Malicious code vulnerability Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectnessMultithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectnessMultithreaded currectness Multithreaded currectnessMultithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectness Multithreaded currectnessMultithreaded currectnessPerformancePerformancePerformancePerformancePerformancePerformancePerformancePerformanceSecuritySecuritySecurity|DodgyDescription是否必须修正(NP_BOOLEAN_RETURN_NULL)必须修正(JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)必须修正(CN_IDIOM)(CN_IDIOM_NO_SUPER_CALL)(CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)必须修正(SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)必须修正(DP_DO_INSIDE_DO_PRIVILEGED)必须修正(IMSE_DONT_CATCH_IMSE)必须修正(NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)(NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)必须修正(DE_MIGHT_DROP)(DE_MIGHT_IGNORE)必须修正(AM_CREATES_EMPTY_JAR_FILE_ENTRY)(AM_CREATES_EMPTY_ZIP_FILE_ENTRY)必须修正(EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)必须修正(FI_FINALIZER_NULLS_FIELDS)(FI_FINALIZER_ONLY_NULLS_FIELDS)必须修正(J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)必须修正(OS_OPEN_STREAM)(OS_OPEN_STREAM_EXCEPTION_PATH)(ODR_OPEN_DATABASE_RESOURCE)(ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)必须修正(UI_INHERITANCE_UNSAFE_GETRESOURCE)必须修正(ISC_INSTANTIATE_STATIC_CLASS)必须修正(IT_NO_SUCH_ELEMENT)必须修正(RR_NOT_CHECKED)(SR_NOT_CHECKED)必须修正(ES_COMPARING_PARAMETER_STRING_WITH_EQ)(ES_COMPARING_STRINGS_WITH_EQ)(RC_REF_COMPARISON)(EC_NULL_ARG)(EC_UNRELATED_CLASS_AND_INTERFACE)(EC_UNRELATED_INTERFACES)(EC_UNRELATED_TYPES)必须修正(BIT_AND)(BIT_AND_ZZ)(BIT_IOR)(BIT_SIGNED_CHECK)(BIT_SIGNED_CHECK_HIGH_BIT)必须修正(RV_RETURN_VALUE_IGNORED)(RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)(RV_EXCEPTION_NOT_THROWN)必须修正(NM_WRONG_PACKAGE_INTENTIONAL)(NM_WRONG_PACKAGE)(NM_VERY_CONFUSING_INTENTIONAL)(NM_VERY_CONFUSING)(NM_CONFUSING)(NM_METHOD_CONSTRUCTOR_CONFUSION)必须修正(EQ_SELF_NO_OBJECT)(EQ_DONT_DEFINE_EQUALS_FOR_ENUM) (EQ_SELF_USE_OBJECT)(CO_SELF_NO_OBJECT)(HE_HASHCODE_NO_EQUALS)(HE_HASHCODE_USE_OBJECT_EQUALS)必须修正必须修正必须修正必须修正必须修正必须修正(NP_DEREFERENCE_OF_READLINE_VALUE)(NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE) (NP_TOSTRING_COULD_RETURN_NULL)(NP_CLONE_COULD_RETURN_NULL)(NP_ALWAYS_NULL)(NP_ALWAYS_NULL_EXCEPTION)建议修正建议修正必须修正必须修正必须修正必须修正(EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC) (EQ_ALWAYS_FALSE)(EQ_ALWAYS_TRUE)(EQ_COMPARING_CLASS_NAMES)(EQ_GETCLASS_AND_CLASS_CONSTANT) (EQ_UNUSUAL)必须修正必须修正必须修正必须修正必须修正建议修正(NP_IMMEDIATE_DEREFERENCE_OF_READLINE) (RV_01_TO_INT)(DM_RUN_FINALIZERS_ON_EXIT)(DM_STRING_CTOR)(DM_STRING_VOID_CTOR)建议修正必须修正必须修正建议修正建议修正(SE_NO_SERIALVERSIONID) (SE_METHOD_MUST_BE_PRIVATE) (WS_WRITEOBJECT_SYNC)(RS_READOBJECT_SYNC)(SE_INNER_CLASS)必须修正必须修正必须修正必须修正必须修正(DLS_DEAD_LOCAL_STORE_IN_RETURN)(EC_BAD_ARRAY_COMPARE)(DLS_OVERWRITTEN_INCREMENT)(ICAST_BAD_SHIFT_AMOUNT)(ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT) (DMI_BAD_MONTH)必须修正必须修正必须修正必须修正建议修正必须修正(SI_INSTANCE_BEFORE_FINALS_ASSIGNED) (IC_INIT_CIRCULARITY)必须修正建议修正(FI_PUBLIC_SHOULD_BE_PROTECTED)(FI_EMPTY)(FI_NULLIFY_SUPER)(FI_MISSING_SUPER_CALL)(FI_USELESS)(FI_EXPLICIT_INVOCATION)必须修正(IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)必须修正(SQL_BAD_PREPARED_STATEMENT_ACCESS)(SQL_BAD_RESULTSET_ACCESS)必须修正(RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)(RE_POSSIBLE_UNINTENDED_PATTERN)(RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)必须修正(BOA_BADLY_OVERRIDDEN_ADAPTER)必须修正(TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED)(TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED)(TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK)必须修正(SA_FIELD_SELF_ASSIGNMENT)(SA_FIELD_DOUBLE_ASSIGNMENT)必须修正(MF_METHOD_MASKS_FIELD)(MF_CLASS_MASKS_FIELD)必须修正(NP_NULL_ON_SOME_PATH)(NP_GUARANTEED_DEREF)必须修正(SA_FIELD_SELF_COMPARISON)(SA_LOCAL_SELF_COMPARISON)(SA_FIELD_SELF_COMPUTATION)(SA_LOCAL_SELF_COMPUTATION)(SA_FIELD_DOUBLE_ASSIGNMENT)必须修正(SA_FIELD_SELF_COMPARISON)(SA_LOCAL_SELF_COMPARISON)(SA_FIELD_SELF_COMPUTATION)(SA_LOCAL_SELF_COMPUTATION)必须修正(UR_UNINIT_READ)必须修正(GC_UNRELATED_TYPES)(DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)(DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)(DMI_VACUOUS_SELF_COLLECTION_CALL)必须修正(NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE)必须修正(IL_INFINITE_LOOP)必须修正(IL_CONTAINER_ADDED_TO_ITSELF)(IL_INFINITE_RECURSIVE_LOOP)必须修正(IL_CONTAINER_ADDED_TO_ITSELF)(IL_INFINITE_RECURSIVE_LOOP)必须修正(IJU_SUITE_NOT_STATIC)(IJU_NO_TESTS)(IJU_BAD_SUITE_METHOD)必须修正(QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)必须修正(RpC_REPEATED_CONDITIONAL_TEST)必须修正(SIO_SUPERFLUOUS_INSTANCEOF)必须修正(STI_INTERRUPTED_ON_CURRENTTHREAD)(STI_INTERRUPTED_ON_UNKNOWNTHREAD)必须修正(UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)必须修正(VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG)必须修正(BC_BAD_CAST_TO_ABSTRACT_COLLECTION) (BC_BAD_CAST_TO_CONCRETE_COLLECTION) (BC_UNCONFIRMED_CAST)(BC_IMPOSSIBLE_CAST)(BC_IMPOSSIBLE_INSTANCEOF)(BC_VACUOUS_INSTANCEOF)(NP_NULL_INSTANCEOF)建议修正建议修正建议修正必须修正必须修正建议修正必须修正(DLS_DEAD_STORE_OF_CLASS_LITERAL) (DLS_DEAD_LOCAL_STORE)(DLS_DEAD_LOCAL_STORE_OF_NULL)(IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)必须修正建议修正建议修正必须修正(FE_FLOATING_POINT_EQUALITY)(FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)建议修正必须修正(UCF_USELESS_CONTROL_FLOW)(UCF_USELESS_CONTROL_FLOW_NEXT_LINE)建议修正必须修正(VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED) (VA_FORMAT_STRING_ILLEGAL)(VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT) (VA_FORMAT_STRING_MISSING_ARGUMENT)(VA_FORMAT_STRING_BAD_ARGUMENT)(VA_FORMAT_STRING_BAD_CONVERSION)必须修正必须修正必须修正必须修正必须修正必须修正(ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL) (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND) (ICAST_IDIV_CAST_TO_DOUBLE)必须修正必须修正建议修正(SF_SWITCH_FALLTHROUGH)(SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)建议修正必须修正(NP_UNWRITTEN_FIELD)(UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR) (UWF_NULL_FIELD)(UWF_UNWRITTEN_FIELD)(SS_SHOULD_BE_STATIC)(URF_UNREAD_FIELD)(UUF_UNUSED_FIELD)必须修正建议修正必须修正必须修正建议修正建议修正建议修正(RV_CHECK_FOR_POSITIVE_INDEXOF)建议修正(DMI_UNSUPPORTED_METHOD)建议修正(CI_CONFUSED_INHERITANCE)建议修正(IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD)建议修正(DB_DUPLICATE_BRANCHES)(DB_DUPLICATE_SWITCH_CLAUSES)建议修正(QF_QUESTIONABLE_FOR_LOOP)建议修正(SA_LOCAL_SELF_ASSIGNMENT)建议修正(DMI_NONSERIALIZABLE_OBJECT_WRITTEN)建议修正(NS_NON_SHORT_CIRCUIT)(NS_DANGEROUS_NON_SHORT_CIRCUIT)建议修正(NP_LOAD_OF_KNOWN_NULL_VALUE)建议修正(MTIA_SUSPECT_STRUTS_INSTANCE_FIELD)建议修正(PZLA_PREFER_ZERO_LENGTH_ARRAYS)建议修正(RI_REDUNDANT_INTERFACES)建议修正(REC_CATCH_EXCEPTION)建议修正(XFB_XML_FACTORY_BYPASS)建议修正(OBL_UNSATISFIED_OBLIGATION)建议修正(MS_EXPOSE_REP)(EI_EXPOSE_REP)(EI_EXPOSE_REP2)(EI_EXPOSE_STATIC_REP2)必须修正(MS_OOI_PKGPROTECT)(MS_FINAL_PKGPROTECT)(MS_PKGPROTECT)(MS_MUTABLE_ARRAY)(MS_MUTABLE_HASHTABLE)(MS_CANNOT_BE_FINAL)(MS_SHOULD_BE_FINAL)必须修正(DC_DOUBLECHECK)必须修正(ESync_EMPTY_SYNC)必须修正(IS2_INCONSISTENT_SYNC)(IS_FIELD_NOT_GUARDED)(MSF_MUTABLE_SERVLET_FIELD)必须修正(JLM_JSR166_LOCK_MONITORENTER)必须修正(MWN_MISMATCHED_NOTIFY)(MWN_MISMATCHED_WAIT)必须修正(NN_NAKED_NOTIFY)必须修正(RU_INVOKE_RUN)必须修正(SWL_SLEEP_WITH_LOCK_HELD)必须修正(SP_SPIN_ON_FIELD)必须修正(TLW_TWO_LOCK_WAIT)必须修正(UW_UNCOND_WAIT)必须修正(UL_UNRELEASED_LOCK)(UL_UNRELEASED_LOCK_EXCEPTION_PATH)必须修正(UG_SYNC_SET_UNSYNC_GET)必须修正(LI_LAZY_INIT_STATIC)(LI_LAZY_INIT_UPDATE_STATIC)必须修正(ML_SYNC_ON_UPDATED_FIELD)必须修正(SC_START_IN_CTOR)必须修正(STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)(STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)(STCAL_STATIC_CALENDAR_INSTANCE)(STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)必须修正(NP_SYNC_AND_NULL_CHECK_FIELD)必须修正(WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)必须修正(ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD)必须修正(VO_VOLATILE_REFERENCE_TO_ARRAY)必须修正(WA_NOT_IN_LOOP)(NO_NOTIFY_NOT_NOTIFYALL)(WA_AWAIT_NOT_IN_LOOP)必须修正(UPM_UNCALLED_PRIVATE_METHOD)建议修正(HSC_HUGE_SHARED_STRING_CONSTANT)建议修正(ITA_INEFFICIENT_TO_ARRAY)建议修正(DM_FP_NUMBER_CTOR)(DM_NUMBER_CTOR)建议修正(SBSC_USE_STRINGBUFFER_CONCATENATION)建议修正(DMI_BLOCKING_METHODS_ON_URL)(DMI_COLLECTION_OF_URLS)建议修正(UM_UNNECESSARY_MATH)建议修正(WMI_WRONG_MAP_ITERATOR)建议修正(HRS_REQUEST_PARAMETER_TO_COOKIE)(HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)(XSS_REQUEST_PARAMETER_TO_JSP_WRITER)(XSS_REQUEST_PARAMETER_TO_SEND_ERROR)(XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER)必须修正(SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)(SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)必须修正(DMI_EMPTY_DB_PASSWORD)(DMI_CONSTANT_DB_PASSWORD)(DMI_USELESS_SUBSTRING)(DMI_HARDCODED_ABSOLUTE_FILENAME)必须修正必须修正建议修正建议修正。

FindBugs规则整理_中文版

FindBugs规则整理_中文版

o)方法不能对参数 的类型做任何的假设。 equals(Object o)方法不能对参数 o 的类型做任何的假设。 比较此对象与指定的对象。 对象与指定的对象 null, 比较此对象与指定的对象。当且仅当该参数不为 null,并 且是表示与此对象相同的类型的对象时, 类型的对象时 true。 且是表示与此对象相同的类型的对象时,结果才为 true。 4. BC: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE) 随机创建对象只使用过一次就抛弃 5. BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK) 检查位操作符运行是否合理 ((event.detail & SWT.SELECTED) > 0) If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '> 0'. 6. CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM) 按照惯例,实现此接口的类应该使用公共方法重写 Object.clone(它是受保护的),以获得有关重写此方法的 详细信息。此接口不 包含 clone 方法。因此,因为某个对 象实现了此接口就克隆它是不可能的,应该实现此接口的类 应该使用公共方法重写 Object.clone 7. CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL) 一个非 final 类型的类定义了 clone()方法而没有调用 super.clone()方法。例如:B 扩展自 A,如果 B 中 clone 方 法调用了 spuer.clone(),而 A 中的 clone 没有调用 spuer.clone(),就会造成结果类型不准确。要求 A 的 clone 方法中调用 spuer.clone()方法。 8. CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)

FindBugs错误说明对照表

FindBugs错误说明对照表

rule.findbugs.BX_BOXING_IMMEDIATELY_=性能- 基本类型包装之后立刻解包rule.findbugs.IJU_SETUP_NO_=使用错误- TestCase定义的setUp没有调用super.setUp()rule.findbugs.TQ_ALWAYS_VALUE_USED_WHERE_NEVER_=使用错误- 某个值使用了注解限制类型,但是这个限制永远不会发生rule.findbugs.TLW_TWO_LOCK_=多线程错误- 等待两个被持有的锁rule.findbugs.RV_01_TO_=使用错误- 0至1的随机数被当做整数0rule.findbugs.NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABL =高危- 参数必须非null但是标记为可为nullrule.findbugs.RV_ABSOLUTE_VALUE_OF_RANDOM_=使用错误- 尝试计算32位随机整数的绝对值rule.findbugs.EC_INCOMPATIBLE_ARRAY_=使用错误- 使用equals()比较不兼容的数组rule.findbugs.UL_UNRELEASED_LOCK_EXCEPTION_=多线程错误- 方法没有在所有异常路径释放锁rule.findbugs.SE_NONSTATIC_=不良实践- serialVersionUID 不是static的rule.findbugs.UCF_USELESS_CONTROL_=高危- 无用控制流rule.findbugs.BC_IMPOSSIBLE_=使用错误- 不可能的转换rule.findbugs.XSS_REQUEST_PARAMETER_TO_SEND_=安全风险- servlet的反射导致跨站脚本漏洞rule.findbugs.DM_NEW_FOR_=性能- 仅为了获得一个方法就创建了一个对象rule.findbugs.OBL_UNSATISFIED_=试验- 方法可能在清理流或资源时失败rule.findbugs.UW_UNCOND_=多线程错误- 无条件等待rule.findbugs.DLS_DEAD_LOCAL_STORE_OF_=高危- 把null设置给不会用到的局部变量rule.findbugs.NM_CLASS_NAMING_=类名应该以大写字母开头rule.findbugs.RC_REF_COMPARISON_BAD_PRACTICE_=使用错误- 怀疑对两个布尔值的引用进行比较rule.findbugs.MWN_MISMATCHED_=多线程错误- 不匹配的notify()rule.findbugs.NM_VERY_=错误- 非常容易迷惑的方法名rule.findbugs.FI_NULLIFY_=不良实践- 空Finalizer禁用了超类的finalizerrule.findbugs.MTIA_SUSPECT_STRUTS_INSTANCE_=高危- 继承了struts Action的类使用了实例变量rule.findbugs.DM_STRING_=性能- 方法调用了效率很低的new String(String)构造方法rule.findbugs.STCAL_INVOKE_ON_STATIC_DATE_FORMAT_=多线程错误- 调用静态DateFormatrule.findbugs.NP_NULL_PARAM_DEREF_=使用错误- 非虚拟方法调用向非空参数传入了nullrule.findbugs.FI_=不良实践- 应该删除空的finalizerrule.findbugs.CD_CIRCULAR_=试验- 类间存在循环引用rule.findbugs.EC_UNRELATED_=使用错误- 使用equals()比较不同类型rule.findbugs.EI_EXPOSE_STATIC_=恶意代码漏洞- 把可变对象保存到静态字段中可能会暴露内部静态状态rule.findbugs.DMI_INVOKING_TOSTRING_ON_ANONYMOUS_=错误- 对数组执行toStringrule.findbugs.SIC_INNER_SHOULD_BE_STATIC_=性能- 可以重构成一个静态内部类rule.findbugs.STI_INTERRUPTED_ON_=错误- 在thread实例上调用了静态Thread.interrupted()方法_IDIOM_NO_SUPER_=不良实践- clone方法没有调用super.clone()rule.findbugs.VA_FORMAT_STRING_BAD_=错误用法- 格式化字符串占位符与传入的参数不匹配rule.findbugs.EQ_DOESNT_OVERRIDE_=高危- 类没有覆盖父类的equals方法rule.findbugs.BC_IMPOSSIBLE_DOWNCAST_OF_=错误用法- 集合转换为数组元素时发生的类型转换错误rule.findbugs.SE_NO_SUITABLE_CONSTRUCTOR_FOR_=不良实践- 类是可扩展的,但是没有提供无参数的构造方法rule.findbugs.TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SIN =错误用法- 数值需要类型标示,但是却标记为未知rule.findbugs.SIC_INNER_SHOULD_BE_STATIC_NEEDS_=性能- 可以筹够成一个静态内部类rule.findbugs.EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_=不良实践- equals检测不兼容的参数操作rule.findbugs.RV_RETURN_VALUE_OF_PUTIFABSENT_=错误用法- 忽略了putIfAbsent的返回值,传递给putIfAbsent的值被重用rule.findbugs.STCAL_INVOKE_ON_STATIC_CALENDAR_=多线程错误- 调用静态Calendarrule.findbugs.MS_CANNOT_BE_=恶意代码漏洞- 字段不是final的,不能防止恶意代码的攻击rule.findbugs.IS_INCONSISTENT_=多线程错误- 不一致的同步rule.findbugs.SE_NO_=不良实践- 类是可序列化的,但是没有定义serialVersionUIDrule.findbugs.EI_EXPOSE_=恶意代码漏洞- 可能暴露内部实现,通过与可变对象引用协作rule.findbugs.NM_METHOD_CONSTRUCTOR_=错误用法- 明显的方法/构造方法混淆rule.findbugs.ICAST_INTEGER_MULTIPLY_CAST_TO_=高危- 整形乘法的结果转换为long型rule.findbugs.QF_QUESTIONABLE_FOR_=高危- for循环中存在复杂,微妙或者错误的自增rule.findbugs.DLS_DEAD_STORE_OF_CLASS_=错误用法- 类中保存了无用字符rule.findbugs.NM_FUTURE_KEYWORD_USED_AS_MEMBER_=不良实践- 使用了未来java版本中成为关键字的标识rule.findbugs.BC_VACUOUS_=高危- instanceof会一直返回truerule.findbugs.INT_VACUOUS_BIT_=高危- 在整形上进行位操作时有一些位上出现空洞rule.findbugs.NP_NULL_=错误用法- 一个已知的null值被检测它是否是一个类型的实例rule.findbugs.SIC_THREADLOCAL_DEADLY_=错误用法- 非静态内部类和ThreadLocal的致命结合rule.findbugs.EQ_=高危- 罕见的equals方法rule.findbugs.IJU_NO_=错误用法- TestCase没有任何测试rule.findbugs.EQ_OVERRIDING_EQUALS_NOT_=错误用法- equals方法覆盖了父类的equals可能功能不符rule.findbugs.XFB_XML_FACTORY_=高危- 方法直接调用了xml接口的一个具体实现rule.findbugs.SWL_SLEEP_WITH_LOCK_=多线程错误- 方法在获得锁时调用了Thread.sleep()_=不良实践- 类实现了Cloneable ,但是没有定义或使用clone方法rule.findbugs.WA_AWAIT_NOT_IN_=多线程错误- 未在循环中使用的Condition.await()rule.findbugs.DM_FP_NUMBER_=性能- 方法调用了低效的浮点书构造方法;应该使用静态的valueOf代替rule.findbugs.SF_SWITCH_NO_=Switch语句中没有包含defaultrule.findbugs.NP_NULL_ON_SOME_PATH_FROM_RETURN_=高危- 调用返回返回值可能出现null值rule.findbugs.NP_CLONE_COULD_RETURN_=不良实践- Clone方法可能返回nullrule.findbugs.MS_OOI_=恶意代码漏洞- 属性应该从接口中移除并将访问权限设置为包保护rule.findbugs.DM_BOXED_PRIMITIVE_=性能- 方法使用了装箱的基本类型只为了调用toStringrule.findbugs.EQ_ABSTRACT_=不良实践- 抽象类定义了协变的equals方法rule.findbugs.DM_STRING_=性能- 方法调用了String的toString()方法rule.findbugs.SE_METHOD_MUST_BE_=错误用法- 方法必须是private 的为了让序列化正常工作rule.findbugs.DL_SYNCHRONIZATION_ON_=多线程错误- 在Boolean 上使用同步可能导致死锁rule.findbugs.UWF_UNWRITTEN_=错误用法- 未赋值属性rule.findbugs.IS2_INCONSISTENT_=多线程错误- 不一致的同步rule.findbugs.IM_AVERAGE_COMPUTATION_COULD_=高危- 计算平均值可能溢出rule.findbugs.BIT_SIGNED_CHECK_HIGH_=错误用法- 检查位运算的符号rule.findbugs.FL_MATH_USING_FLOAT_=错误用法- 方法进行数学运算时使用了浮点数的精度rule.findbugs.WS_WRITEOBJECT_=多线程错误- 类的writeObject()方法是同步的,但是没有做其他事情rule.findbugs.RV_RETURN_VALUE_=错误用法- 方法忽略了返回值rule.findbugs.SQL_NONCONSTANT_STRING_PASSED_TO_=安全风险- 非常量的字符串传递给方法执行SQL语句rule.findbugs.JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_=不良实践- 不可变的类的属性应该是finalrule.findbugs.AM_CREATES_EMPTY_ZIP_FILE_=不良实践- 创建了一个空的zip文件的入口rule.findbugs.DM_NEXTINT_VIA_=性能- 使用Random的nextInt 方法来获得一个随机整数,而不是nextDoublerule.findbugs.UI_INHERITANCE_UNSAFE_=不良实践- 如果类被扩展,GetResource的使用可能就是不安全的rule.findbugs.SIO_SUPERFLUOUS_=错误用法- 不必要的类型检测使用instanceof操作符rule.findbugs.EQ_OTHER_NO_=错误用法- equals()方法定义,但是没有覆盖equals(Object)M_USELESS_ABSTRACT_=试验- 抽象方法已经在实现的接口中定义了rule.findbugs.MTIA_SUSPECT_SERVLET_INSTANCE_=高危- 扩展Servlet的类使用了实例变量rule.findbugs.DM_USELESS_=多线程错误- 使用默认的空run方法创建了一个线程rule.findbugs.ML_SYNC_ON_UPDATED_=多线程错误- 方法在一个修改了的属性上进行了同步rule.findbugs.CO_SELF_NO_=不良实践- 协变的compareTo()定义rule.findbugs.BC_UNCONFIRMED_=高危- 未检查/未证实的类型转换rule.findbugs.FI_FINALIZER_NULLS_=不良实践- Finalizer空属性rule.findbugs.BIT_=错误用法- 不兼容的位掩码(BIT_AND)rule.findbugs.FE_FLOATING_POINT_=高危- 测试浮点数相等rule.findbugs.TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK. name=错误用法- 值不要求有类型标示,但是标记为未知rule.findbugs.NP_NULL_PARAM_=错误用法- 方法调用把null传递给一个非null参数rule.findbugs.FB_MISSING_EXPECTED_=试验- findbugs丢失了期待或需要的警告rule.findbugs.DMI_INVOKING_HASHCODE_ON_=错误用法- 在数组上调用了hashCoderule.findbugs.QBA_QUESTIONABLE_BOOLEAN_=错误用法- 方法在布尔表达式中分配了boolean文字rule.findbugs.SA_FIELD_SELF_=错误用法- 属性自己与自己进行了比较rule.findbugs.UR_UNINIT_READ_CALLED_FROM_SUPER_=错误用法- 父类的构造方法调用未初始化属性的方法rule.findbugs.ES_COMPARING_PARAMETER_STRING_WITH_=不良实践- 比较字符串参数使用了== 或!=rule.findbugs.INT_BAD_COMPARISON_WITH_NONNEGATIVE_=错误用法- 错误比较非负值与负数rule.findbugs.INT_BAD_COMPARISON_WITH_SIGNED_=错误用法- 错误比较带符号的byterule.findbugs.IO_APPENDING_TO_OBJECT_OUTPUT_=错误用法- 尝试向一个对象输出流添加信息rule.findbugs.FI_MISSING_SUPER_=不良实践- Finalizer没有调用父类的finalizerrule.findbugs.VA_FORMAT_STRING_EXTRA_ARGUMENTS_=错误用法- 传递了多余实际使用的格式化字符串的参数rule.findbugs.HE_EQUALS_USE_=不良实践- 类定义了equals(),但使用了Object.hashCode()rule.findbugs.IJU_BAD_SUITE_=错误用法- TestCase声明了一个错误的suite方法rule.findbugs.DMI_CONSTANT_DB_=安全风险- 硬编码了数据库密码rule.findbugs.REC_CATCH_=高危- 捕获了没有抛出的异常rule.findbugs.PS_PUBLIC_=高危- 类在公用接口中暴露了同步和信号rule.findbugs.EC_UNRELATED_=错误用法- 调用equals()比较不同的接口类型rule.findbugs.UCF_USELESS_CONTROL_FLOW_NEXT_=错误用法- 执行到下一行的无用流程控制rule.findbugs.LG_LOST_LOGGER_DUE_TO_WEAK_=试验- OpenJDK中存在潜在的丢失logger的风险,因为弱引用rule.findbugs.NP_UNWRITTEN_=错误用法- 读取未初始化的属性rule.findbugs.DMI_UNSUPPORTED_=高危- 调用不支持的方法rule.findbugs.RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE. name=高危- 重复比较非空值和nullrule.findbugs.EC_BAD_ARRAY_=错误用法- 调用equals(),与==效果一样rule.findbugs.EI_EXPOSE_=恶意代码漏洞- 可能通过返回一个可变对象的引用暴露了内部实现rule.findbugs.NP_DEREFERENCE_OF_READLINE_=高危- 没有判断readLine()的结果是否为空rule.findbugs.UPM_UNCALLED_PRIVATE_=性能- 从未用到的私有方法rule.findbugs.NP_NULL_ON_SOME_=错误用法- 可能出现空指针引用rule.findbugs.NP_EQUALS_SHOULD_HANDLE_NULL_=不良实践- equals()方法没有检测null参数rule.findbugs.EC_NULL_=错误用法- 使用空参数调用equals()rule.findbugs.SE_BAD_FIELD_=不良实践- 非序列化值保存在序列化类的实例变量中rule.findbugs.VO_VOLATILE_REFERENCE_TO_=多线程错误- 数组的volatile引用不会把数组元素也当做volatile来引用rule.findbugs.NP_SYNC_AND_NULL_CHECK_=多线程错误- 同步和空值检测发生在同一个属性上rule.findbugs.DM_=不良实践- 方法调用了System.exit(...)rule.findbugs.RC_REF_=不良实践- 怀疑进行了引用比较rule.findbugs.SE_NO_SUITABLE_=不良实践- 类是可序列化的,但是父类没有定义无参数构造方法rule.findbugs.DC_=多线程错误- 可能对属性进行了双重检测rule.findbugs.DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_=错误用法- 在int上调用了Double.longBitsToDoublerule.findbugs.RpC_REPEATED_CONDITIONAL_=错误用法- 重复判断条件rule.findbugs.WMI_WRONG_MAP_=性能- keySet迭代是低效的,使用entrySet代替rule.findbugs.DLS_DEAD_LOCAL_=高危- 未用的局部变量rule.findbugs.INT_BAD_REM_BY_=错误用法- 整数剩余模1rule.findbugs.RV_RETURN_VALUE_IGNORED_BAD_=不良实践- 方法忽略异常返回值rule.findbugs.SA_LOCAL_SELF_=高危- 局部变量的自我赋值rule.findbugs.MS_SHOULD_BE_=恶意代码漏洞- 属性不是final,但是应该设置成finalrule.findbugs.SIC_INNER_SHOULD_BE_=性能- 应该是一个静态内部类rule.findbugs.NP_GUARANTEED_=错误用法- null值一定会被调用rule.findbugs.SE_READ_RESOLVE_MUST_RETURN_=不良实践- readResolve方法必须返回Objectrule.findbugs.NP_LOAD_OF_KNOWN_NULL_=高危- 加载了已知的null值rule.findbugs.BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION.na me=性能- 基本数据被装箱又被拆箱_IMPLEMENTS_CLONE_BUT_NOT_=不良实践- 类定义了clone()但没有实现Cloneablerule.findbugs.CO_ABSTRACT_=不良实践- 抽象类定义了协变的compareTo()方法rule.findbugs.BAC_BAD_APPLET_=试验- 错误的Applet构造方法依赖未初始化的AppletStubrule.findbugs.EQ_GETCLASS_AND_CLASS_=不良实践- equals方法因为子类失败rule.findbugs.DB_DUPLICATE_SWITCH_=高危- 在两个switch语句中使用了相同的代码rule.findbugs.DB_DUPLICATE_=高危- 在两个分支中使用了相同的代码rule.findbugs.UOE_USE_OBJECT_=试验- 在final类上调用了equals,但是没有覆盖Object的equals方法rule.findbugs.FI_=不良实践- Finalizer除了调用父类的finalizer以外什么也没做rule.findbugs.NP_ALWAYS_=错误用法- 调用了null指针rule.findbugs.DMI_VACUOUS_SELF_COLLECTION_=错误用法- 集合的调用不能被感知rule.findbugs.DLS_DEAD_LOCAL_STORE_IN_=错误用法- 返回语句中的无用的赋值rule.findbugs.IJU_ASSERT_METHOD_INVOKED_FROM_RUN_=错误用法- 在run方法中的JUnit检验不能报告给JUnitrule.findbugs.DMI_EMPTY_DB_=安全风险- 空的数据库密码rule.findbugs.DM_BOOLEAN_=性能- 方法调用了低效的Boolean构造方法;使用Boolean.valueOf(...)代替rule.findbugs.BC_IMPOSSIBLE_=错误用法- 不可能转型rule.findbugs.BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_=不良实践- Equals方法不应该假设任何有关参数类型的事宜rule.findbugs.RV_EXCEPTION_NOT_=错误用法- 异常创建后就丢弃了,没有抛出rule.findbugs.VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_=错误用法- 基本类型数组传递给一个期待可变对象类型参数的方法rule.findbugs.LI_LAZY_INIT_UPDATE_=多线程错误- 错误的延迟初始化和更新静态属性rule.findbugs.SA_FIELD_SELF_=错误用法- 属性自身赋值rule.findbugs.EQ_ALWAYS_=错误用法- equals方法一直返回falserule.findbugs.DMI_RANDOM_USED_ONLY_=不良实践- Random对象创建后只用了一次rule.findbugs.NM_CLASS_NOT_=不良实践- Class没有继承Exception,虽然名字像一个异常rule.findbugs.SA_LOCAL_DOUBLE_=高危- 给局部变量双重赋值rule.findbugs.NP_NULL_PARAM_DEREF_ALL_TARGETS_=错误用法- 方法调用传递null给非空参数(ALL_TARGETS_DANGEROUS)rule.findbugs.NP_TOSTRING_COULD_RETURN_=不良实践- toString方法可能返回nullrule.findbugs.BC_BAD_CAST_TO_ABSTRACT_=高危- 转换成抽象集合值得怀疑rule.findbugs.NM_LCASE_=类定义了hashcode(); 应该是hashCode()吧?rule.findbugs.RU_INVOKE_=多线程错误- 在线程中调用了run(你的意思是再启动一次么?)rule.findbugs.DMI_INVOKING_TOSTRING_ON_=错误用法- 调用了数组的toStringrule.findbugs.NM_METHOD_NAMING_=方法名应该以小写字母开头rule.findbugs.RCN_REDUNDANT_COMPARISON_TWO_NULL_=高危- 重复比较两个null值rule.findbugs.SA_LOCAL_SELF_=错误用法- 对一个变量进行无意义的自我计算(比如x & x)rule.findbugs.MS_MUTABLE_=恶意代码漏洞- 属性是可变的Hashtablerule.findbugs.RV_DONT_JUST_NULL_CHECK_=高危- 方法丢掉了readLine的结果,在检测它是非空之后。

FindBugs_简明教程

FindBugs_简明教程

FindBugs 简明教程前言:本文重点在FindBugs的入门使用相关的介绍内容请看本文后面的推荐链接FindBugs的使用入门下面将介绍2种方式利用FindBugs去自检代码第一种适用于Eclipse下开发的应用程序第二种适用于Framework层的局部代码准备方面a.FingBugs Eclipse plug-in/eclipseb.FindBugs tools with Swing Interface/findbugs/findbugs-1.3.9.zip?download 1.使用步骤2.1Eclipse下安装FindBugs plug-in1)点击Install New Software 进行安装2)点击Add之后在弹出的地址框中填入FindBugs Plug-in的地址3)将FindBugs Feature勾选并点击Next4)猛点Next5)勾选accept 并点击Finish6)Waiting…7)点击OK8)安装成功后提示重启Eclipse,点击Restart Now2.2Eclipse下使用FindBugs, 在此使用ApiDemo为例1)右键点击工程,点击FindBugs2)FindBugs分析完成后自动跳转到Bug Explorer. 点击一个Bug自动定位到代码行,然后点击代码行最左端的”Bugs”,在Properties中显示该Bug的详细情况建议修改的方式等等(自动生成的R文件相关的可略过)3)点击Windows->Preferences->Java->FindBugs 可配置FindBugs自检规则4)自检完成后可将FindBugs结果以xml的形式保存下来作为凭证2.3利用FindBugs tool自检(适用于局部代码自检例如framework修改的代码在此举例)1)下载FindBugstools with Swing Interface 并解压点进bin下的findbugs.bat2) 将待检代码文件及对应的class文件准备好并导入并点击完成这里拿AbsListView.java举例将out\target\common\obj\JAVA_LIBRARIES\framework_intermediates\classes.jar 中有关AbsListView的class都拿出来包括内部类3)根据分析结果定位到代码进行修改下面有相关的Bug行数及方法名及变量名2.4运用Findbugs 命令行的方式检查指定的类或者jar命令行常用命令:$FINDBUGS_HOME $/bin/findbugs -textui [options…] <Jar or class file path>Options:-low (Report all bugs)-medium (Report medium and high priority bug. This is the default setting.)-high (Report only high priority bugs.)-xml (Produce the bug reports as XML)-help (displays help information for the FindBugs command line user interface)利用基本基本命令去检查会在命令行中打印每个Bug的信息以行为单位使用了-xml 参数后打印的是xml报告可以将其导入Fingbugs plug-in或者Swing GUI中查看使用命令行的时候为了方便查看及保存可以把结果重定向到文本中FindBugs推荐资料IBM-FindBugs详细说明/developerworks/cn/java/j-findbug1//developerworks/cn/java/j-findbug2/FindBugs官网/Baidu百科FindBugs/view/2367937.htm。

详解FindBugs的各项检测器

详解FindBugs的各项检测器

模式
-
速度

缺陷类别
-
类型 edu.umd.cs.findbugs.detect.FindBugsSummaryStats
说明 这个检测器仅仅收集分析过程相关的汇总统计信息。
报告模式 无
1.8 FunctionThatMightBeMistakenForProcedures
模式
-
速度

缺陷类别
-
类型
模式
-
速度

缺陷类别
-
类型 edu.umd.cs.findbugs.detect.NoteSuppressedWarnings




使

说明 edu.umd.cs.findbugs.annotations.NoteSuppressWarnings 注 解 的 警
告。
报告模式 无
1.17 ReflectiveClasses
当在一个应当只能使用非null值的上下文环境中使用了一个可能为null的值那么findnullderef检测器会使用这些信息生成警告报告模式无115notenonnullreturnvalues模式速度慢缺陷类别类型eduumdcsfindbugsdetectnotenonnullreturnvalues说明分析应用程序中所有的方法以便于确定哪个方法总是返回非null的值
缺陷类别
-
类型 edu.umd.cs.findbugs.detect.CalledMethods
说明 构建在被分析类中调用的所有方法的数据库,供其他检测器使用。
报告模式 无
1.4 CheckCalls
模式
-
速度

FindBugs错误分析说明

FindBugs错误分析说明

FindBugs 错误修改指南版本号 修改描述 作者 日期1.0 新建 cantellow 2011-5-241.1 补充英文标识及出错案例 卫缺 2011-6-9使用方法:复制你的Pattern id ,然后用快捷键Ctrl + F 查找,即可快速定位。

所有的解释和解决方式只是可能和建议,大多数时候需要根据实际情况而定。

Findbugs 也有少量的误报,需要大家自己甄别。

1. EC_UNRELATED_TYPESBug: Call to equals() comparing different typesPattern id: EC_UNRELATED_TYPES, type: EC, category: CORRECTNESS 解释:两个不同类型的对象调用equals 方法,如果equals 方法没有被重写,那么调用object 的==, 永远不会相等;如果equals 方法被重写,而且含有instanceof 逻辑,那么还是不会相等。

解决方法:应该改为str.toString()2. IM_BAD_CHECK_FOR_ODDBug: Check for oddness that won't work for negative numbers Pattern id: IM_BAD_CHECK_FOR_ODD, type: IM, category: STYLE 解释:如果row 是负奇数,那么row % 2 == -1, 解决方法:考虑使用x & 1 == 1或者x % 2 != 0Class doesn't override equals in superclassFindBugsÌ«ÉñÆæÁË~~3. NP_ALWAYS_NULLPattern: Null pointer dereferenceid: NP_ALWAYS_NULL, type: NP, category: CORRECTNESSA null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed.4. RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUEBug: Redundant nullcheck of bean1, which is known to be non-nullPattern id: RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE, type: RCN, category: STYLEThis method contains a redundant check of a known non-null value against the constant null.这种方法包含了一个称为非空对空值的不断重复检查。

FindBugs规则整理

FindBugs规则整理

FindBugs规则整理/jdsjlzx/article/details/21472253//aya19880214/article/details/41958445/link?url=r4KX6A37_GW1xHkb7ezYJ-2S_2wQ-E_nB9Yps_mkj35nsKaFnEizt7AqWck_diLRXRIvWquVPZ__9wC8jXFmCNjh6_r6I485H81oTBUQtoe /zm_21/article/details/47276581命令⾏⽅式1./findbugs -textui -low -html -output report.html ./findbugs/outputfiles/常见参数说明:-home 定义findbugs2软件存放位置-low 提交警告及任何级别以上报告-medium 提交中,⾼级报告(默认)-high 只提交⾼级警告-xml 警告以 xml输出-html 警告以 html输出-output 定义输出的⽂件名-onlyAnalyze 只分析指定的 class/package-exclude 忽略指定的 class/package (以xml定义过滤的命名)-include 只输出指定的 class/package (以xml定义过滤的命名)过滤规则⽰例⽂件:opencdk_exclude_filter.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39<?xml version="1.0" encoding="UTF-8"?><FindBugsFilter><!-- android-support-v4.jar:包过滤 --><Match><Package name="~android\.support\.v4.*" /></Match><!-- 类过滤、⽅法 --><Match><Class name="com.opencdk.MusicActivity" /><Method name="getMusicName" /></Match><Match><Class name="com.opencdk.VideoActivity" /></Match><!-- Match all doublecheck violations in these methods of "AnotherClass". --> <Match><Class name="com.opencdk.AnotherClass" /><Or><Method name="nonOverloadedMethod" /><Method name="frob" params="int,ng.String" returns="void" /><Method name="blat" params="" returns="boolean" /></Or><Bug code="DC" /></Match><!-- All bugs in test classes, except for JUnit-specific bugs --><Match><Class name="~.*\.*Test" /><Not><Bug code="IJU" /></Not></Match></FindBugsFilter>。

FindBugs安装及使用说明

FindBugs安装及使用说明

FindBug安装及使用说明目录1.简介 (3)1.1说明 (3)1.2环境要求 (3)1.3注意事项 (3)2.FINDBUGS安装 (3)2.1在线安装 (3)2.2离线安装 (9)3.FINDBUGS使用 (10)3.1F IND B UGS操作 (10)3.2F IND B UGS常见故障模式 (11)3.2.1NP_NULL_ON_SOME_PATH: Possible null pointer dereference (11)3.2.2DLS_DEAD_LOCAL_STORE: Dead store to local variable (11)3.2.3BX_BOXING_IMMEDIATELY_UNBOXED: Primitive value is boxed and then immediately unboxed .. 123.2.4DM_NUMBER_CTOR: Method invokes inefficient Number constructor; use static valueOf instead 123.2.5Cloneable Not Implemented Correctly (CN) (12)3.2.6OBL_UNSATISFIED_OBLIGATION: Method may fail to clean up stream or resource (12)3.2.7Double Checked Locking (DC) (13)3.2.8Dropped Exception (DE) (14)3.2.9Suspicious Equals Comparison (EC) (14)3.2.10Bad Covariant Definition of Equals (Eq) (15)3.2.11Equal Objects Must Have Equal Hashcodes (HE) (15)3.2.12Static Field Modifiable By Untrusted Code (MS) (15)3.2.13Null Pointer Dereference (NP), Redundant Comparison to Null (RCN) (16)3.2.14Non-Short-Circuit Boolean Operator (NS) (17)3.2.15Open Stream (17)3.2.16Read Return Should Be Checked (RR) (17)3.2.17Return Value Should Be Checked (RV) (18)3.2.18Non-serializable Serializable class (SE) (18)3.2.19Uninitialized Read In Constructor (UR) (18)3.2.20Unconditional Wait (UW) (19)3.2.21Wait Not In Loop (Wa) (19)1.简介1.1说明FindBugs 是一个java bytecode静态分析工具,它可以帮助java工程师提高代码质量以及排除隐含的缺陷。

findbugs扫描规则

findbugs扫描规则
一个静态字段可能被恶意代码或另外一个包所改变的。字段可以放到protected包中也可以定义为final类型的以避免此问题。
MS_MUTABLE_ARRAY
一个定义为final类型的静态字段引用一个数组时它可以被恶意代码或在另其他包中所使用。这些代码可以自由修改数组的内容。
MS_OOI_PKGPROTECT
UR_UNINIT_READ
此构造方法中使用了一个尚未赋值的字段或属性。
UWF_UNWRITTEN_FIELD
方法被超类的构造函数调用时,在当前类中的字段或属性还没有被初始化。
可能运行时出错的代码
规则
问题与解决方法
OBL_UNSATISFIED_OBLIGATION
这种方法可能无法清除(关闭,处置)一个流,数据库
EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS
equals方法检查不一致的操作。两个类根本就是父子关系而
去调用equals方法去判读对象是否相等。
EQ_COMPARETO_USE_OBJECT_EQUALS
类中定义了compareTo方法但是继承了Object中的
and uses Object.hashCode()
SR_NOT_CHECKED
InputStream.skip()方法忽略返回的多个字符,如果对结果
没有检查就没法正确处理用户跳过少量字符请求的情况
正确性检查:
规则
问题与解决方法
BC_IMPOSSIBLE_CAST
不可能的类转换,执行时会抛出ClassCastException
RR_NOT_CHECKED
InputStream.read方法忽略返回的多个字符,如果对结果没有检查就没法正确处理用户读取少量字符请求的情况。

FindBugs错误分析说明

FindBugs错误分析说明

FindBugs错误修改指南使用方法:复制你的Pattern id,然后用快捷键Ctrl + F查找,即可快速定位。

所有的解释和解决方式只是可能和建议,大多数时候需要根据实际情况而定。

Findbugs也有少量的误报,需要大家自己甄别。

1. EC_UNRELATED_TYPESBug: Call to equals() comparing different typesPattern id: EC_UNRELATED_TYPES, type: EC, category: CORRECTNESS解释:两个不同类型的对象调用equals方法,如果equals方法没有被重写,那么调用object的==,永远不会相等;如果equals方法被重写,而且含有instanceof逻辑,那么还是不会相等。

解决方法:应该改为str.toString()2. IM_BAD_CHECK_FOR_ODDBug: Check for oddness that won't work for negative numbersPattern id: IM_BAD_CHECK_FOR_ODD, type: IM, category: STYLE解释:如果row是负奇数,那么row % 2 == -1,解决方法:考虑使用x & 1 == 1或者x % 2 != 0Class doesn't override equals in superclass3. NP_ALWAYS_NULLPattern: Null pointer dereferenceid: NP_ALWAYS_NULL, type: NP, category: CORRECTNESSA null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed.4. RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUEBug: Redundant nullcheck of bean1, which is known to be non-null Pattern id: RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE, type: RCN, category: STYLEThis method contains a redundant check of a known non-null value against the constant null.这种方法包含了一个称为非空对空值的不断重复检查。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)
为使用静态方法而创建一个实例对象。调用静态方法时只需要使用类名+静态方法名就可以了。
It: Iterator next() method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT)
CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)
按照惯例,实现此接口的类应该使用公共方法重写 (它是受保护的),以获得有关重写此方法的详细信息。此接口不 包含 clone 方法。因此,因为某个对象实现了此接口就克隆它是不可能的,应该实现此接口的类应该使用公共方法重写
This call to a generic collection method passes an argument while compile type Object where a specific type from the generic type parameters is expected. Thus, neither the standard Java type system nor static analysis can provide useful information on whether the object being passed as a parameter is of an appropriate type.
CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)
类中定义了clone方法但是它没有实现Cloneable接口
Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)
public static void initLogging() throws Exception {
Logger logger = ("");
(new FileHandler()); nfo("Some message");
Even when is not negative, it seems good practice to use '!= 0' instead of '> 0'.
XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)
在代码中在JSP输出中直接写入一个HTTP参数,这会造成一个跨站点的脚本漏洞。
Experimental
序号
Description
用==或者!=去比较String类型的对象
Eq: Abstract class defines covariant equals() method(EQ_ABSTRACT_SELF)
Eq: Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)
}
static CircularClassInitialization foo = ;
}
IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)
捕捉违法的监控状态异常,例如当没有获取到对象锁时使用其wait和notify方法
子类继承了父类的equals方法却使用了Object的hashCode方法
IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)
子类在父类未初始化之前使用父类对象实例
方法可能忽略异常
DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)
不要用removeAll方法去clear一个集合
DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)
规则整理
规则整理
Findbugs中把影响代码质量分为以下几个部分:
Security关于代码安全性防护
序号
Description
备注
Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD)
代码中创建DB的密码时采用了写死的密码。
类加载器只能建立在特殊的方法体内
Dm: Method invokes (...) (DM_EXIT)
在方法中调用(...)语句,考虑用RuntimeException来代替
Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)
public class CircularClassInitialization {
static class InnerClassSingleton extends CircularClassInitialization {
static InnerClassSingleton singleton = new InnerClassSingleton();
equals方法检查不一致的操作。两个类根本就是父子关系而去调用equals方法去判读对象是否相等。
public boolean equals(Object o) {
if (o instanceof Foo)
return (((Foo)o).name);
else if (o instanceof String)
return (o);
else return false;
Eq: Class defines compareTo(...) and uses () (EQ_COMPARETO_USE_OBJECT_EQUALS)
类中定义了compareTo方法但是继承了Object中的compareTo方法
Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)
类定义了hashCode方法去没有定义equal方法
HE: Class defines equals() and uses () (HE_EQUALS_USE_HASHCODE)
一个类覆写了equals方法,没有覆写hashCode方法,使用了Object对象的hashCode方法
HE: Class inherits equals() and uses () (HE_INHERITS_EQUALS_USE_HASHCODE)
在方法中调用了或者方法,因为这样做是很危险的。
ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)
用==或者!=方法去比较String类型的参数
ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)
HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)
方法定义了equals方法却没有定义hashCode方法
HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)
备注
LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)
OpenJDK的引入了一种潜在的不兼容问题,特别是,的行为改变时。它现在使用内部弱引用,而不是强引用。–logger配置改变,它就是丢失对logger的引用,这本是一个合理的变化,但不幸的是一些代码对旧的行为有依赖关系。这意味着,当进行垃圾收集时对logger配置将会丢失。例如:
抽象类中定义了多个compareTo()方法,正确的是覆写Comparable中的compareTo方法,方法的参数为Object类型,如下例:
int compareTo(T o)比较此对象与指定对象的顺序。
Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)
FI: Empty finalizer should be deleted (FI_EMPTY)
为空的finalizer方法应该删除。一下关于finalizer的内容省略
GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)
相关文档
最新文档