a.Class names shouldn't shadow simple name of implemented interface
This class/interface has a simple name that is identical to that of an implemented/extended interface, except that the interface is in a different package (e.g., alpha.Foo extends beta.Foo). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidentally define methods that do not override methods in their superclasses.
c.Class names should start with an upper case letter
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
类名首字母应该大写
1publicclasstestTest {}
d.Field names should start with a lower case letter
Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized.
A mutable public field is defined inside a public enum, thus can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world. Consider declaring this field final and/or package-private.
b.Public enum method unconditionally sets its field
This public method declared in public enum unconditionally sets enum field, thus this field can be changed by malicious code or by accident from another package. Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world. Consider removing this method or declaring it package-private.
This method returns a value that is not checked. The return value should be checked since it can indicate an unusual or unexpected function execution. For example, the File.delete() method returns false if the file could not be successfully deleted (rather than throwing an Exception). If you don't check the result, you won't notice if the method invocation signals unexpected behavior by returning an atypical return value.
The method creates an IO stream object, does not assign it to any fields, pass it to other methods that might close it, or return it, and does not appear to close the stream on all paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.
a.Adding elements of an entry set may fail due to reuse of Entry objects
The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.
a.Class defines clone() but doesn't implement Cloneable
This class defines a clone() method but the class doesn't implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended.
This 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.
This class implements the Comparator interface. You should consider whether or not it should also implement the Serializable interface. If a comparator is used to construct an ordered collection such as a TreeMap, then the TreeMap will be serializable only if the comparator is also serializable. As most comparators have little or no state, making them serializable is generally easy and good defensive programming.
This format string include a newline character (\n). In format strings, it is generally preferable better to use %n, which will produce the platform-specific line separator.
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 interned using the String.intern() method, the same string value may be represented by two different String objects. Consider using the equals(Object) method instead
There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
b.Possible null pointer dereference in method on exception path
A 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.
c.Non-virtual method call passes null for non-null parameter
A possibly-null value is passed to a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.
The program is dereferencing a field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.
This method call passes a null value for a non-null method parameter. Either the parameter is annotated as a parameter that should always be non-null, or analysis has shown that it will always be dereferenced.
g.Value is null and guaranteed to be dereferenced on exception path
There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions)
A value is checked here to see whether it is null, but this value can't be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference. Essentially, this code and the previous dereference disagree as to whether this value is allowed to be null. Either the check is redundant or the previous dereference is erroneous.
Loads a byte value (e.g., a value loaded from a byte array or returned by a method with return type byte) and performs a bitwise OR with that value. Byte values are sign extended to 32 bits before any any bitwise operations are performed on the value. Thus, if b[0] contains the value 0xff, and x is initially 0, then the code ((x << 8) | b[0]) will sign extend 0xff to get 0xffffffff, and thus give the value 0xffffffff as the result. In particular, the following code for packing a byte array into an int is badly wrong: int result = 0; for(int i = 0; i < 4; i++) result = ((result << 8) | b[i]); The following idiom will work instead: int result = 0; for(int i = 0; i < 4; i++) result = ((result << 8) | (b[i] & 0xff));
a.Integral value cast to double and then passed to Math.ceil
This code converts an integral value (e.g., int or long) to a double precision floating point number and then passing the result to the Math.ceil() function, which rounds a double to the next higher integer value. This operation should always be a no-op, since the converting an integer to a double should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.ceil was intended to be performed using double precision floating point arithmetic.
a.MessageFormat supplied where printf style format expected(严重)
A method is called that expects a Java printf format string and a list of arguments. However, the format string doesn't contain any format specifiers (e.g., %s) but does contain message format elements (e.g., {0}). It is likely that the code is supplying a MessageFormat string when a printf-style format string is required. At runtime, all of the arguments will be ignored and the format string will be returned exactly as provided without any formatting.
b.More arguments are passed than are actually used in the format string
A format-string method with a variable number of arguments is called, but more arguments are passed than are actually used by the format string. This won't cause a runtime exception, but the code may be silently omitting information that was intended to be included in the formatted string.
A String function is being invoked and "." or "|" is being passed to a parameter that takes a regular expression as an argument. Is this what you intended? For example s.replaceAll(".", "/") will return a String in which every character has been replaced by a '/' character s.split(".") always returns a zero length array of String "ab|cd".replaceAll("|", "/") will return "/a/b/|/c/d/" "ab|cd".split("|") will return array with six (!) elements: [, a, b, |, c, d]
The code here uses a regular expression that is invalid according to the syntax for regular expressions. This statement will throw a PatternSyntaxException when executed.
Signed bytes can only have a value in the range -128 to 127. Comparing a signed byte with a value outside that range is vacuous and likely to be incorrect. To convert a signed byte b to an unsigned value in the range 0..255, use 0xff & b
The code invokes toString on an array, which will 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. See Programming Puzzlers, chapter 3, puzzle 12.
a.A parameter is dead upon entry to a method but overwritten
The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller.
This code is casting the result of calling toArray() on a collection to a type more specific than Object[], as in: String[] getAsArray(Collection c) { return (String[]) c.toArray(); } This 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 from a collection is to use c.toArray(new String[]); or c.toArray(new String[c.size()]); (the latter is slightly more efficient). There is one common/known exception exception to this. The toArray() method of lists returned by Arrays.asList(...) will return a covariantly typed array. For example, Arrays.asArray(new String[] { "a" }).toArray() will return a String []. FindBugs attempts to detect and suppress such cases, but may miss some.
This field is never written. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.
All writes to this field are of the constant value null, and thus all reads of the field will return null. Check for errors, or remove it if it is useless.
属性曾经设置为null,看具体代码,有些类属性没用了要去掉或者重新定义成局部变量。
13.Confusing method name
a.Very confusing method names
The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other.
a.Possible null pointer dereference due to return value of called method
The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed.
The variable referenced at this point is known to be null due to an earlier check against null. Although this is valid, it might be a mistake (perhaps you intended to refer to a different variable, or perhaps the earlier check to see if the variable is null should have been a check to see if it was non-null).
The program is dereferencing a public or protected field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception.
a.Exception is caught when Exception is not thrown
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs. A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below: try { ... } catch (RuntimeException e) { throw e; } catch (Exception e) { ... deal with all non-runtime exceptions ... }
This instanceof test will always return true (unless the value being tested is null). Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error. If you really want to test the value for being null, perhaps it would be clearer to do better to do a null test rather than an instanceof test.
The code computes the average of two integers using either division or signed right shift, and then uses the result as the index of an array. If the values being averaged are very large, this can overflow (resulting in the computation of a negative average). Assuming that the result is intended to be nonnegative, you can use an unsigned right shift instead. In other words, rather that using (low+high)/2, use (low+high) >>> 1 This bug exists in many earlier implementations of binary search and merge sort. Martin Buchholz found and fixed it in the JDK libraries, and Joshua Bloch widely publicized the bug pattern.
This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. Note that Sun's javac compiler often generates dead stores for final local variables. Because FindBugs is a bytecode-based tool, there is no easy way to eliminate these false positives.
未用的局部变量,但有可能是误报
7.Casting from integer values
a.Result of integer multiplication cast to long
This code performs integer multiply and then converts the result to a long, as in: long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; } If the multiplication is done using long arithmetic, you can avoid the possibility that the result will overflow. For example, you could fix the above code to: long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; } or static final long MILLISECONDS_PER_DAY = 24L*3600*1000; long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; }
a.Switch statement found where default case is missing
This method contains a switch statement where default case is missing. Usually you need to provide a default case. Because the analysis only looks at the generated bytecode, this warning can be incorrect triggered if the default case is at the end of the switch statement and the switch statement doesn't contain break statements for other cases.
Our analysis shows that this object is useless. It's created and modified, but its value never go outside of the method or produce any side-effect. Either there is a mistake and object was intended to be used or it can be removed. This analysis rarely produces false-positives. Common false-positive cases include: - This object used to implicitly throw some obscure exception.
未使用的对象应删除掉,不然有可能抛出异常
1 List vals2 = new ArrayList<>();
2 vals2.add("2018-05-05");
3 vals2.add("2018-05-09");
4//vo2.setValues(vals2);
10.Misuse of static fields
a.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.
静态对象不要多次实例化
11.Bad use of return value from method
a.Return value of method without side effect is ignored
This code calls a method and ignores the return value. However our analysis shows that the method (including its implementations in subclasses if any) does not produce any effect other than return value. Thus this call can be removed. We are trying to reduce the false positives as much as possible, but in some cases this warning might be wrong. Common false-positive cases include: - The method is designed to be overridden and produce a side effect in other projects which are out of the scope of the analysis. - The method is called to trigger the class loading which may have a side effect. - The method is called just to get some exception. If you feel that our assumption is incorrect, you can use a @CheckReturnValue annotation to instruct FindBugs that ignoring the return value of this method is acceptable.
A Thread object is passed as a parameter to a method where a Runnable is expected. This is rather unusual, and may indicate a logic error or cause unexpected behavior.
No writes were seen to this public/protected field. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.
未被使用的public 或 protected 属性,
14.Unread field
a.Unread public/proected field
This field is never read. The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.
未被使用的public 或 protected 属性
15.Unused field
a.Unused public or protected field
This field is never used. The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.
未被使用的public 或 protected 属性
四 Experimental(可试验代码/有潜在风险代码,主要是资源回收方面)
1.Unsatisfied obligation to clean up stream or resource
a.Method may fail to clean up stream or resource on checked exception
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns. This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback, either: send email to [email protected] file a bug report: http://findbugs.sourceforge.net/reportingBugs.html In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us. See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for a description of the analysis technique.
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.
a.Method invokes inefficient new String(String) constructor
Using the java.lang.String(String) constructor wastes memory because the object so constructed will be functionally indistinguishable from the String passed as a parameter. Just use the argument String directly.
方法调用了效率很低的new String(String)构造方法,只需直接使用String
1 String regexUnion = new String("^(130|131|132|155|156|185|186|145|176)[0-9]{8}$");
Creating new instances of java.lang.Boolean wastes memory, since Boolean objects are immutable and there are only two useful values of this type. Use the Boolean.valueOf() method (or Java 1.5 autoboxing) to create Boolean objects instead.
方法调用了低效的Boolean构造方法;使用Boolean.valueOf(...)代替
1mDebugLog.append("\n").append(String.format("IsTelePhoneVoice:{0}", (new Boolean(mIsTelePhoneVoice)).toString()));
2 mDebugLog.append("\n").append(String.format("IsTelePhoneVoice:{0}", Boolean.valueOf(mIsTelePhoneVoice)));
c.Method invokes inefficient new String() constructor
Creating a new java.lang.String object using the no-argument constructor wastes memory because the object so created will be functionally indistinguishable from the empty string constant "". Java guarantees that identical string constants will be represented by the same String object. Therefore, you should just use the empty string constant directly.
使用了new String()
1 tA_RecordsChangeLogBLL.AddUpdateLog(people.getPeopleNo(), new String()"", peopleModelAfter,
2 TaRecordsChangeLog.EnmuTableType.TB_People.getValue(), "整车业务", "");
2.Inefficient Map Iterator
a.Inefficient use of keySet iterator instead of entrySet iterator
This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration. Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly. For example: // This is bad String s = ""; for (int i = 0; i < field.length; ++i) { s = s + field[i]; }
// This is better StringBuffer buf = new StringBuffer(); for (int i = 0; i < field.length; ++i) { buf.append(field[i]); } String s = buf.toString();
loop里面应该使用StringBuffer替换+号
1/** 2 * 返回一个随机数
3 *
4 * @param i
5 * @return 6*/ 7publicstatic String getRandom(int i) {
8 Random jjj = new Random();
9// int suiJiShu = jjj.nextInt(9);10if (i == 0)
11return "";
12 String jj = "";
13 StringBuffer jj=new StringBuffer();
14for (int k = 0; k < i; k++) {
15 jj = jj + jjj.nextInt(9);
16 jj.append(jjj.nextInt(9));
17 }
18return jj;
19 }
4.Questionable Boxing of primitive value
a.Boxed value is unboxed and then immediately reboxed
A boxed value is unboxed and then immediately reboxed.
c.Methiod allocates a boxed primitive just to call toString
A boxed primitive is allocated just to call toString(). It is more effective to just use the static form of toString which takes the primitive value. So, Replace... With this... new Integer(1).toString() Integer.toString(1) new Long(1).toString() Long.toString(1) new Float(1.0).toString() Float.toString(1.0) new Double(1.0).toString() Double.toString(1.0) new Byte(1).toString() Byte.toString(1) new Short(1).toString() Short.toString(1) new Boolean(true).toString() Boolean.toString(true)
d.Method invokes inefficient Number constructor;use static valueOf instead
Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster. Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same. Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.
This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made static.
This field is never read. Consider removing it from the class.
未使用的属性,建议移除
七 Malicious code vulnerability(如果公开会被恶意攻击的代码)
1.Mutable static field
a.Field isn't final but should be
This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability.
应该使用final修饰
b.Public static method may expose internal representation
A 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.
A mutable static field could be changed by malicious code or by accident. The field could be made package protected to avoid this vulnerability.
属性应该是package protected
d.Field is a mutable collection
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
e.Field is a mutable collection which should be package protected
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. The field could be made package protected to avoid this vulnerability. Alternatively you may wrap this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
与d一致处理
2.Storing reference to mutable object
a.May expose internal representation by incorporating reference to mutable object(严重)
This code stores a reference to an 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 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.
3.Method returning array may expose internal representation
a.May expose internal representation by returning reference to mutable object
Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. 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.
androi中提到了布尔数组;
布尔数组默认的是false, 并且只会打印false或者是true
布尔数组的例子; 根据字符数组创建布尔数组
char[] c = {'p','u','b','l','i','c'};
//根据字符数组的长度创建布尔数组的个数
boolean[] b = new bool
文章摘自:http://blog.csdn.net/yangwawa19870921/article/details/7553181
在编写HQL时,可能会出现这种代码:
select a.name,b.age from TableA a left join TableB b on a.id=b.id
如果这是HQL,那么这段代码就是错误的,因为HQL不支持
1. 简单的for循环
public static void main(String[] args) {
for (int i = 1, y = i + 10; i < 5 && y < 12; i++, y = i * 2) {
System.err.println("i=" + i + " y="
异常信息本地化
Spring Security支持将展现给终端用户看的异常信息本地化,这些信息包括认证失败、访问被拒绝等。而对于展现给开发者看的异常信息和日志信息(如配置错误)则是不能够进行本地化的,它们是以英文硬编码在Spring Security的代码中的。在Spring-Security-core-x
近来工作中遇到这样的两个需求
1. 给个Date对象,找出该时间所在月的第一天和最后一天
2. 给个Date对象,找出该时间所在周的第一天和最后一天
需求1中的找月第一天很简单,我记得api中有setDate方法可以使用
使用setDate方法前,先看看getDate
var date = new Date();
console.log(date);
// Sat J
MyBatis的update元素的用法与insert元素基本相同,因此本篇不打算重复了。本篇仅记录批量update操作的
sql语句,懂得SQL语句,那么MyBatis部分的操作就简单了。 注意:下列批量更新语句都是作为一个事务整体执行,要不全部成功,要不全部回滚。
MSSQL的SQL语句
WITH R AS(
SELECT 'John' as name, 18 as