findbugs检测出的问题(一)

1  Comparison of String objects using == or !=

    例,override equals方法时容易犯错

if(this.topic != key.getTopic())
    return false;

2 Dead store to newStatusRecord

    定义局部变量后没有引用

 

3 Invocation of toString on values
   直接调用数组的toString方法

public  Query createQuery(String hql, Object values[],Session session){
  logger.debug(values);
  logger.debug((new StringBuilder()).append("hql=[").append(hql).append("] ").append(((Object) 

}

 正确的例子,调用Arrays.toString()和Arrays.deepToString()方法。

 import java.util.Arrays;

class A{
	
}
class B{
	@Override
	public String toString() {
		return "BBBBB";
	}
}
public class Test {
	public static void main(String[] args) {

		
		Object [] a = {new Integer(0),new Boolean(true),true,new A(),new B()};
		
		Object[][]b ={{new A(),new B()},{new A(),new B()},{new A(),new B()}};
		System.out.println(Arrays.deepToString(b));
		
	}
}

 


4 ignores exceptional return value of java.io.File.mkdirs()

 忽略了返回值,应当含有返回值

		public void initFolder() {
if (!exitDir.isDirectory())  {
			exitDir.mkdirs();
			logger.info("===Finishing create exit trade image folder!====");
		}
	}

 

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.

5 不使用new String()定义空的字符串

String alarmCodeCond = new String();

 应当

 

String alarmCodeCond = "";

 
6 invokes inefficient new Short(short) constructor; use Short.valueOf(short) instead
    JVM缓存数字常量

Short aShort = new Short(12);

 应当

Short aShort = Short.valueOf(12);

7 方法命名习惯,首字母小写

     The method name LaneHandShakeService(Short) doesn't start with a lower case letter

     Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

 

8  一个primtive的类型的值经过box后马上unbox

Primitive value is boxed then unboxed to perform primitive coercion

exitRecord.setEnOperatorId(new Long(transactRecord.getEnoperatorID()).intValue());

 应当直接强制类型转换

exitRecord.setEnOperatorId((int)transactRecord.getEnoperatorID());

 

9 Call to equals() comparing different types
 使用equals()方法比较不同的类,

 反例

		StringBuilder builder = new StringBuilder("nihao");
		String string = "nihao";
		builder.equals(string);

 10  Check for oddness that won't work for negative numbers
 检查奇数的方法:

 反例

			if (i % 2 == 1) {
				//...
			}

 

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

 

11 Load of known null value,null值的不当使用

反例:

if (devIds == null && devIds.size() == 0) {		//...		}

 

if (null != tempList || tempList.size() != 0) {
            //...
}

 

if (batchNo == null) {
			throw new Exception("the No. " + batchNo
					+ " is not exists!");
		}

 12  Method call passes null for nonnull parameter

    对参数为null的情况没做处理

    例:

  

public void method1() {
 		String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		long ipCount = countIpAddress(ip); // 可能会传入空引用
                               //...
}

	long countIpAddress(String ip) {
		long ipNum = 0;
		String[] ipArray = ip.split("\\.");
}

 修改后:

public void method1() {
 		String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		long ipCount = countIpAddress(ip); // 可能会传入空引用
                               //...
}

	long countIpAddress(String ip) {
		long ipNum = 0;
		if (ip == null) {
			return 0;          //或者抛出异常
		}
		String[] ipArray = ip.split("\\.");
                               //...
}

   注意:函数入口需要交验入参的合法性。

 

13 Method concatenates strings using + in a loop
 在循环里使用字符串连接,效率低,应该使用StringBuilder/StringBuffer

 例:

 

				String writeData = "";
				for (int i = 0; i < 10; i++) {
					writeData = writeData + "a";
				}

 14 Method may fail to close database resource

   没有释放数据库资源

	public ResultSet callProcedure(String procedure) {
		Session ses = getSessionForUpdate();
		ResultSet rs = null;
		try {
			Connection conn = ses.connection();
			conn.setAutoCommit(false);
			CallableStatement statement = conn.prepareCall(procedure); //may fail to close CallableStatement

			rs = statement.executeQuery();
			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ses.close();
			} catch (SQLException e) {
				throw e;
			}
		}
		return rs;
	}

   应当修改为:

  

	public ResultSet callProcedure(String procedure) {
		Session ses = getSessionForUpdate();
		ResultSet rs = null;
		CallableStatement statement = null;
		try {
			Connection conn = ses.connection();
			conn.setAutoCommit(false);
			statement = conn.prepareCall(procedure);

			rs = statement.executeQuery();
			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				statement.close();
				ses.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return rs;
	}

 15 Method may fail to close stream
    没有关闭流,可能会导致文件描述符泄露,应该在finally中关闭

   例:

		try {
			FileInputStream in = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(in);
			BufferedReader reader = new BufferedReader(inputStreamReader);
			//...

			in.close();
			inputStreamReader.close();
			reader.close();
		} catch (IOException e) {

		}

   修改为:

		FileInputStream in = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		try {
			in = new FileInputStream(file);
			inputStreamReader = new InputStreamReader(in);
			reader = new BufferedReader(inputStreamReader);
			// ...

		} catch (IOException e) {

		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				inputStreamReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

 16 Method might ignore exception
   

This method might ignore an exception.  In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.

应该将异常 处理、打印或者抛出

反例:

 try {
     //...

     } catch (Exception e) {


     }

 

17 Class defines non-transient non-serializable instance field readerTypeInfo

 一个实现了Serializable接口的类,含有非transient 和非serializable 的实例对象域。

 

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

 

18 Nullcheck of value previously dereferenced

 前面获取的对象,现在引用的时候没有交验是否为null

反例:

		Reader reader = null;
		try {
			reader = this.getReaderByName(readerBasicInfo.getByName());
		}  catch (Exception e1) {
			e1.printStackTrace();
			return ReaderStateConst.FAIL;
		}

		DependenceRelation dependenceRelation = new DependenceRelation();
		dependenceRelation.setDescription(reader.getIpAddress());  // 使用前没有做null校验

 

19  Possible null pointer dereference
   可能存在的空引用

 

		capInfo = wrapper.wrapperToClient((ReaderCapabilities) object);

		try {
			if (capInfo != null) {
				transactionDs
						.saveReaderCapabilityCom((ReaderCapabilities) object);
			}
		} catch (RuntimeException e) {
			capInfo.setDetailMsg(ReaderStateConst.DB_OPT_FAIL);
			return capInfo;
		}

		capInfo.setDetailMsg(ReaderStateConst.SUCCESSFUL);   //capInfo可能为null

 

20 引用前需要做空校验

	public synchronized void remove(String batNo, int count) {
		List taskList = commandMap.get(batNo);
		synchronized (taskList) {	//使用前需要作null check
			//...
		}
	}

 

你可能感兴趣的:(findbugs检测出的问题(一))