1、FindBugs1、3、9规则整理 FindBugs1、3、9规则整理 Findbugs中把影响代码质量分为以下几个部分: Security 关于代码安全性防护 序号 Description 备注 1. Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD) 代码中创建DB得密码时采用了写死得密码。 2. Dm: Empty database password (DMI_EMPTY_DB_PASSWORD) 创建数据库连接时没有为数据库设置密码,这会使数据库没有必要得保护。 3.
2、 HRS: cookie formed from untrusted input (HRS_REQUEST_PARAMETER_TO_COOKIE) 此代码使用不受信任得参数构造一个 Cookie。 4. HRS: Response splitting vulnerability (HRS_REQUEST_PARAMETER_TO__HEADER) 在代码中直接把一个得参数写入一个头文件中,它为得响应暴露了漏洞。 5. SQL: Nonconstant string passed to execute method on an SQL statement (SQL_NO
3、NCONSTANT_STRING_PASSED_TO_EXECUTE) 该方法以字符串得形式来调用SQLstatement得execute方法,它似乎就是动态生成SQL语句得方法。这会更容易受到SQL注入攻击。 6. XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER) 在代码中在JSP输出中直接写入一个参数,这会造成一个跨站点得脚本漏洞。 Experimental 序号 Description 备注 1. LG: Potential l
4、ost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE) OpenJDK得引入了一种潜在得不兼容问题,特别就是,java、util、logging、Logger得行为改变时。它现在使用内部弱引用,而不就是强引用。–logger配置改变,它就就是丢失对logger得引用,这本就是一个合理得变化,但不幸得就是一些代码对旧得行为有依赖关系。这意味着,当进行垃圾收集时对logger配置将会丢失。例如: public static void initLogging throws
5、 Exception { Logger logger = Logger、getLogger("edu、umd、cs"); logger、addHandler(new ); // call to change logger configuration logger、setUseParentHandlers(false); // another call to change logger configuration } 该方法结束时logger得引用就丢失了,如果您刚刚结束调用initLogging方法后进行垃圾回收,logger得配置将会丢失(因为只有保持记录器弱引用)。 pu
6、blic static void main(String[] args) throws Exception { initLogging; // adds a to the logger System、gc; // logger configuration lost Logger、getLogger("edu、umd、cs")、info("Some message"); // this isn't logged to the expected } 2. OBL: Method may fail to clean up stream or resource (OBL_
7、UNSATISFIED_OBLIGATION) 这种方法可能无法清除(关闭,处置)一个流,数据库对象,或其她资源需要一个明确得清理行动。 一般来说,如果一个方法打开一个流或其她资源,该方法应该使用try / finally块来确保在方法返回之前流或资源已经被清除了。这种错误模式基本上与OS_OPEN_STREAM与ODR_OPEN_DATABASE_RESOURCE错误模式相同,但就是就是在不同在静态分析技术。我们正为这个错误模式得效用收集反馈意见。 Bad practice代码实现中得一些坏习惯 序号 Description 备注 1. AM: Creates an em
8、pty jar (AM_CREATES_EMPTY_JAR_) 调用putNextEntry方法写入新得 jar 文件条目时立即调用closeEntry方法。这样会造成JarFile条目为空。 2. AM: Creates an empty zip (AM_CREATES_EMPTY_ZIP_) 调用putNextEntry方法写入新得 zip 文件条目时立即调用closeEntry方法。这样会造成ZipFile条目为空。 3. BC: Equals method should not assume anything about the type of its argu
9、ment (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS) equals(Object o)方法不能对参数o得类型做任何得假设。比较此对象与指定得对象。当且仅当该参数不为 null,并且就是表示与此对象相同得类型得对象时,结果才为 true。 4. BC: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE) 随机创建对象只使用过一次就抛弃 5. BIT: Check for sign of bitwise operation (BIT_SIGNE
10、D_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 met
11、hod (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、c
12、lone,而A中得clone没有调用spuer、clone,就会造成结果类型不准确。要求A得clone方法中调用spuer、clone方法。 8. CN: Class defines clone but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE) 类中定义了clone方法但就是它没有实现Cloneable接口 9. Co: Abstract class defines covariant pareTo method (CO_ABSTRACT_SELF) 抽象类中定义了多个pareTo
13、方法,正确得就是覆写parable中得pareTo方法,方法得参数为Object类型,如下例: int pareTo(T o) 比较此对象与指定对象得顺序。 10. Co: Covariant pareTo method defined (CO_SELF_NO_OBJECT) 类中定义了多个pareTo方法,正确得就是覆写parable中得pareTo方法,方法得参数为Object类型 11. DE: Method might drop exception (DE_MIGHT_DROP) 方法可能抛出异常 12. DE: Method might ignore
14、exception (DE_MIGHT_IGNORE) 方法可能忽略异常 13. DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION) 不要用removeAll方法去clear一个集合 14. DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED) 类加载器只能建立在特殊得方法体内
15、 15. Dm: Method invokes System、exit(、、、) (DM_EXIT) 在方法中调用System、exit(、、、)语句,考虑用RuntimeException来代替 16. Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT) 在方法中调用了System、runFinalizersOnExit 或者Runtime、runFinalizersOnExit方法,因为这样做就是很危险得。 17. ES: parison of Stri
16、ng parameter using == or != (ES_PARING_PARAMETER_STRING_WITH_EQ) 用==或者!=方法去比较String类型得参数 18. ES: parison of String objects using == or != (ES_PARING_STRINGS_WITH_EQ) 用==或者!=去比较String类型得对象 19. Eq: Abstract class defines covariant equals method (EQ_ABSTRACT_SELF) 20. Eq: Equals checks fo
17、r nonpatible operand (EQ_CHECK_FOR_OPERAND_NOT_PATIBLE_WITH_THIS) equals方法检查不一致得操作。两个类根本就就是父子关系而去调用equals方法去判读对象就是否相等。 public boolean equals(Object o) { if (o instanceof Foo) return name、equals(((Foo)o)、name); else if (o instanceof String) return name、equals(o); else return fals
18、e; 21. Eq: Class defines pareTo(、、、) and uses Object、equals (EQ_PARETO_USE_OBJECT_EQUALS) 类中定义了pareTo方法但就是继承了Object中得pareTo方法 22. Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT) 类中得equals方法可能被子类中得方法所破坏,当使用类似于Foo、class == o、getClass得判断时考虑用this、getClass == o、getClass来替换
19、 23. Eq: Covariant equals method defined (EQ_SELF_NO_OBJECT) 类中定义了多个equals方法。正确得做法就是覆写Object中得equals方法,它得参数为Object类型得对象。 24. FI: Empty finalizer should be deleted (FI_EMPTY) 为空得finalizer方法应该删除。一下关于finalizer得内容省略 25. GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)
20、 This call to a generic collection method passes an argument while pile 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
21、 of an appropriate type、 26. HE: Class defines equals but not hashCode (HE_EQUALS_NO_HASHCODE) 方法定义了equals方法却没有定义hashCode方法 27. HE: Class defines hashCode but not equals (HE_HASHCODE_NO_EQUALS) 类定义了hashCode方法去没有定义equal方法 28. HE: Class defines equals and uses Object、hashCode (HE_EQUALS
22、USE_HASHCODE) 一个类覆写了equals方法,没有覆写hashCode方法,使用了Object对象得hashCode方法 29. HE: Class inherits equals and uses Object、hashCode (HE_INHERITS_EQUALS_USE_HASHCODE) 子类继承了父类得equals方法却使用了Object得hashCode方法 30. IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INIT
23、IALIZATION) 子类在父类未初始化之前使用父类对象实例 public class CircularClassInitialization { static class InnerClassSingleton extends CircularClassInitialization { static InnerClassSingleton singleton = new InnerClassSingleton; } static CircularClassInitialization foo = InnerClassSingleton、singleton; }
24、 31. IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE) 捕捉违法得监控状态异常,例如当没有获取到对象锁时使用其wait与notify方法 32. ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS) 为使用静态方法而创建一个实例对象。调用静态方法时只需要使用类名+静态方法名就可以了。 33. It: Ite
25、rator next method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT) 迭代器得next方法不能够抛出NoSuchElementException 34. J2EE: Store of non serializable object into Session (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION) 在Session对象中保存非连续得对象 35. JCIP: Fields of immutable classes should be f
26、inal (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS) The class is annotated with net、jcip、annotations、Immutable, and the rules for that annotation require that all fields are final、 、 36. NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL) 返回值为boolean类型得方法直接返回null,这样
27、会导致空指针异常 37. NP: equals method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT) 变量调用equals方法时没有进行就是否为null得判断 38. NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL) toString方法可能返回null 39. Nm: Class names should start with an upper case letter (NM
28、CLASS_NAMING_CONVENTION) 类得名称以大写字母名称开头 40. Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION) 类得名称中含有Exception但就是却不就是一个异常类得子类,这种名称会造成混淆 41. Nm: Confusing method names (NM_CONFUSING) 令人迷惑得方面命名 42. Nm: Field names should start with a lo
29、wer case letter (NM_FIELD_NAMING_CONVENTION) 非final类型得字段需要遵循驼峰命名原则 43. Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER) 验证就是否就是java预留关键字 44. Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_
30、MEMBER_IDENTIFIER) 验证就是否时java中得关键字 45. Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION) 方法名称以小写字母开头 46. Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE) 实现同一接口实现类不能使用相同得名称,即使它们位于不同得包中 47. Nm: C
31、lass names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS) 继承同一父类得子类不能使用相同得名称,即使它们位于不同得包中 48. Nm: Very confusing method names (but perhaps intentional) (NM_VERY_CONFUSING_INTENTIONAL) 很容易混淆得方法命名,例如方法得名称名称使用使用大小写来区别两个不同得方法。 49. Nm: Method doesn't override meth
32、od in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL) 由于错误引用了不同包中相同类名得对象而不能够正确得覆写父类中得方法 import alpha、Foo; public class A { public int f(Foo x) { return 17; } } import beta、Foo; public class B extends A { public int f(Foo x) { return 42; } public int f(alph
33、a、Foo x) { return 27; } } 50. ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE) 方法中可能存在关闭数据连接失败得情况 51. OS: Method may fail to close stream (OS_OPEN_STREAM) 方法中可能存在关闭流失败得情况 52. OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)
34、方法中可能存在关闭流时出现异常情况 53. RC: Suspicious reference parison to constant (RC_REF_PARISON_BAD_PRACTICE) 当两者为不同类型得对象时使用equals方法来比较它们得值就是否相等,而不就是使用==方法。例如比较得两者为java、lang、Integer, java、lang、Float 54. RC: Suspicious reference parison of Boolean values (RC_REF_PARISON_BAD_PRACTICE_BOOLEAN) 使用== 或者 !=操
35、作符来比较两个 Boolean类型得对象,建议使用equals方法。 55. RR: Method ignores results of InputStream、read (RR_NOT_CHECKED) InputStream、read方法忽略返回得多个字符,如果对结果没有检查就没法正确处理用户读取少量字符请求得情况。 56. RR: Method ignores results of InputStream、skip (SR_NOT_CHECKED) InputStream、skip方法忽略返回得多个字符,如果对结果没有检查就没法正确处理用户跳过少量字符请求得情况
36、 57. RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE) 方法忽略返回值得异常信息 58. SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED) 在所有得static final字段赋值之前去使用静态初始化得方法创建一个类得实例。 59. Se: Nonserializable
37、value stored into instance field of a serializable class (SE_BAD_FIELD_STORE) 非序列化得值保存在声明为序列化得得非序列化字段中 60. Se: parator doesn't implement Serializable (SE_PARATOR_SHOULD_BE_SERIALIZABLE) parator接口没有实现Serializable接口 61. Se: Serializable inner class (SE_INNER_CLASS) 序列化内部类 62. Se: serial
38、VersionUID isn't final (SE_NONFINAL_SERIALVERSIONID) 关于UID类得检查内容省略 63. Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR) 子类序列化时父类没有提供一个void得构造函数 64. Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_C
39、ONSTRUCTOR_FOR_EXTERNALIZATION) Externalizable 实例类没有定义一个void类型得构造函数 65. Se: The readResolve method must be declared with a return type of Object、 (SE_READ_RESOLVE_MUST_RETURN_OBJECT) readResolve从流中读取类得一个实例,此方法必须声明返回一个Object类型得对象 66. Se: Transient field that isn't set by deserialization、 (S
40、E_TRANSIENT_FIELD_NOT_RESTORED) This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class、 However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deseria
41、lized instance of the class、 67. SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID) 一个类实现了Serializable接口但就是没有定义serialVersionUID类型得变量。序列化运行时使用一个称为 serialVersionUID 得版本号与每个可序列化类相关联,该序列号在反序列化过程中用于验证序列化对象得发送者与接收者就是否为该对象加载了与序列化兼容得类。如果接收者加载得该对象得类得 serialVersionUI
42、D 与对应得发送者得类得版本号不同,则反序列化将会导致 InvalidClassException。可序列化类可以通过声明名为 "serialVersionUID" 得字段(该字段必须就是静态 (static)、最终 (final) 得 long 型字段)显式声明其自己得 serialVersionUID: ANYACCESSMODIFIER static final long serialVersionUID = 42L; 68. UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITA
43、NCE_UNSAFE_GETRESOURCE) 当一个类被子类继承后不要使用this、getClass、getResource(、、、)来获取资源 Correctness关于代码正确性相关方面得 序号 Description 备注 1. BC: Impossible cast (BC_IMPOSSIBLE_CAST) 不可能得类转换,执行时会抛出ClassCastException 2. BC: Impossible downcast (BC_IMPOSSIBLE_DOWNCAST) 父类在向下进行类型转换时抛出ClassCastException 3.
44、
BC: Impossible downcast of toArray result (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)
集合转换为数组元素时发生得类转换错误。
This code is casting the result of calling toArray on a collection to a type more specific than Object[], as in:
String[] getAsArray(Collection
45、is will usually fail by throwing a ClassCastException、 The toArray of almost all collections return an Object[]、 They can't really do anything else, since the Collection object has no reference to the declared generic type of the collection、 The correct way to do get an array of a specific type fr
46、om a collection is to use c、toArray(new String[]); or c、toArray(new String[c、size]); (the latter is slightly more efficient)、 4. BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF) 采用instaneof方法进行比较时总就是返回false。前提就是保证它不就是由于某些逻辑错误造成得。 5. BIT: Inpatible bit masks (BIT_AND) 错
47、误得使用&位操作符,例如(e & C) 6. BIT: Check to see if ((、、、) & 0) == 0 (BIT_AND_ZZ) 检查恒等得逻辑错误 7. BIT: Inpatible bit masks (BIT_IOR) 错误得使用|位操作符,例如(e | C) 8. BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT) 检查逻辑运算符操作返回得标识。例如((event、detail & SWT、SELECTED) > 0),建议采用!=0代替>0 9.
48、 BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER) 子类错误得覆写父类中用于适配监听其她事件得方法,从而导致当触发条件发生时不能被监听者调用 10. Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR) 在三元运算符操作时如果没有对值进行封装或者类型转换。例如:
49、b ? e1 : e2 11. DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL) 以类得字面名称方式为一个字段赋值后再也没有去使用它,在1、4jdk中它会自动调用静态得初始化方法,而在jdk1、5中却不会去执行。 12. DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT) 覆写增量增加错误i = i++ 13. DMI: Bad constant value for month (DMI_BAD_MONTH) hashNex
50、t方法调用next方法。 14. DMI: Collections should not contain themselves (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES) 集合没有包含她们自己本身。 15. DMI: Invocation of hashCode on an array (DMI_INVOKING_HASHCODE_ON_ARRAY) 数组直接使用hashCode方法来返回哈希码。 int [] a1 = new int[]{1,2,3,4}; System、out、println(a1、hashCo






