java代码优化

来源:互联网 发布:anyview4.0 java下载 编辑:程序博客网 时间:2024/06/06 00:02

1、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.

public static String SUCCESS_CODE="A_C_0001";

加入 final: 

public static final String SUCCESS_CODE="A_C_0001";

保证该变量值不被改变



2、判断相等(equals  、 compareTo)

String str = ...str.equals("someOtherString");//orstr.compareTo("someOtherString");

上面这种代码会有空指针报错。 要改成如下形式。

String str = ..."someOtherString".equals(str);//or"someOtherString".compareTo(str);


3、抓住异常不打印或抛出

try {HttpGet request = new HttpGet(url);// 这里发送get请求HttpClient httpClient = new DefaultHttpClient();HttpResponse response = httpClient.execute(request);if (response.getStatusLine().getStatusCode() == 200) {HttpEntity entity = response.getEntity();result = EntityUtils.toString(entity, "utf-8");// 将entity当中的数据转换为字符串}} catch (Exception e) {logger.error("http请求异常,请求地址{}",url);throw new BizException(CodeMsgMap.error_rpc_wrong);}