




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
FindBugs常見問題指南1
ComparisonofStringobjectsusing==or!=例,overrideequals方法時容易犯錯Java代碼
\o"收藏這段代碼"if(this.topic
!=
key.getTopic())
return
false;2DeadstoretonewStatusRecord
定義局部變量后沒有引用3InvocationoftoStringonvalues
直接調(diào)用數(shù)組的toString方法Java代碼
\o"收藏這段代碼"public
Query
createQuery(String
hql,
Object
values[],Session
session){
logger.debug(values);
logger.debug((new
StringBuilder()).append("hql=[").append(hql).append("]
").append(((Object)
}
正確的例子,調(diào)用Arrays.toString()和Arrays.deepToString()方法。Java代碼
\o"收藏這段代碼"
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));
}
}
4ignoresexceptionalreturnvalueofjava.io.File.mkdirs()
忽略了返回值,應當含有返回值Java代碼
\o"收藏這段代碼"public
void
initFolder()
{
(!exitDir.isDirectory())
{
exitDir.mkdirs();
("===Finishing
create
exit
trade
image
folder!====");
}
Thismethodreturnsavaluethatisnotchecked.Thereturnvalueshouldbecheckedsinceitcanindicateanunusualorunexpectedfunctionexecution.Forexample,theFile.delete()methodreturnsfalseifthefilecouldnotbesuccessfullydeleted(ratherthanthrowinganException).Ifyoudon'tchecktheresult,youwon'tnoticeifthemethodinvocationsignalsunexpectedbehaviorbyreturninganatypicalreturnvalue.5不使用newString()定義空的字符串Java代碼
\o"收藏這段代碼"String
alarmCodeCond
=
new
String();
應當
Java代碼
\o"收藏這段代碼"String
alarmCodeCond
=
"";
例:
Java代碼
\o"收藏這段代碼"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("\\.");
}
修改后:Java代碼
\o"收藏這段代碼"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("\\.");
//...
}
注意:函數(shù)入口需要交驗入?yún)⒌暮戏ㄐ浴?3Methodconcatenatesstringsusing+inaloop
在循環(huán)里使用字符串連接,效率低,應該使用StringBuilder/StringBuffer
例:
Java代碼
\o"收藏這段代碼"String
writeData
=
"";
for
(int
i
=
0;
i
<
10;
i++)
{
writeData
=
writeData
+
"a";
}
14Methodmayfailtoclosedatabaseresource
沒有釋放數(shù)據(jù)庫資源Java代碼
\o"收藏這段代碼"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();
mit();
}
catch
(Exception
e)
{
e.printStackTrace();
}
finally
{
try
{
ses.close();
}
catch
(SQLException
e)
{
throw
e;
}
}
return
rs;
}
應當修改為:
Java代碼
\o"收藏這段代碼"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();
mit();
}
catch
(Exception
e)
{
e.printStackTrace();
}
finally
{
try
{
statement.close();
ses.close();
}
catch
(SQLException
e)
{
e.printStackTrace();
}
}
return
rs;
}
15Methodmayfailtoclosestream
沒有關閉流,可能會導致文件描述符泄露,應該在finally中關閉
例:Java代碼
\o"收藏這段代碼"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)
{
}
修改為:Java代碼
\o"收藏這段代碼"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();
}
}
16Methodmightignoreexception
Thismethodmightignoreanexception.
Ingeneral,exceptionsshouldbehandledorreportedinsomeway,ortheyshouldbethrownoutofthemethod.應該將異常處理、打印或者拋出反例:Java代碼
\o"收藏這段代碼"try
{
//...
}
catch
(Exception
e)
{
}
17Classdefinesnon-transientnon-serializableinstancefieldreaderTypeInfo
一個實現(xiàn)了Serializable接口的類,含有非transient和非serializable的實例對象域。
ThisSerializableclassdefinesanon-primitiveinstancefieldwhichisneithertransient,Serializable,orjava.lang.Object,anddoesnotappeartoimplementtheExternalizableinterfaceorthereadObject()andwriteObject()methods.
Objectsofthisclasswillnotbedeserializedcorrectlyifanon-Serializableobjectisstoredinthisfield.18Nullcheckofvaluepreviouslydereferenced
前面獲取的對象,現(xiàn)在引用的時候沒有交驗是否為null反例:Java代碼
\o"收藏這段代碼"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
Possiblenullpointerdereference
可能存在的空引用
Java代碼
\o"收藏這段代碼"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引用前需要做空校驗Java代碼
\o"收藏這段代碼"public
synchronized
void
remove(String
batNo,
int
count)
{
List<Task>
taskList
=
commandMap.get(batNo);
synchronized
(taskList)
{
//使用前需要作null
check
//...
}
}
21Possiblenullpointerdereferenceinmethodonexceptionpath例Java代碼
List<District>
districts
=
null;
try
{
districts
=
this.getDistricts(ReaderConst.DESC);
}
catch
(Exception
e)
{
e.printStackTrace();
}
if
(start
>=
districts.size())
{
//districts
可能是null
tableData.setTotalCount(0);
return
tableData;
}
22內(nèi)部類沒有引用外部類的屬性/方法的時候,應該作為靜態(tài)內(nèi)部類。Thisclassisaninnerclass,butdoesnotuseitsembeddedreferencetotheobjectwhichcreatedit.
Thisreferencemakestheinstancesoftheclasslarger,andmaykeepthereferencetothecreatorobjectalivelongerthannecessary.
Ifpossible,theclassshouldbemadestatic.
23包裝類的比較應該使用eueqls,要比較值類型,需要強制類型轉(zhuǎn)換后再使用。Thismethodcomparestworeferencevaluesusingthe==
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 風險應對策略的選擇試題及答案
- 高考語文考場應用試題及答案
- 湖北省咸寧市咸安區(qū)2025年八下數(shù)學期末統(tǒng)考試題含解析
- 制定個人學習與發(fā)展路徑計劃
- 細分市場的品牌定位研究計劃
- 提升領導力的實踐方法計劃
- 計算機科學專業(yè)進階學習策略試題及答案
- 計算機輔助翻譯(CAT)軟件應用試題及答案
- 2024年陜西科技大學輔導員考試真題
- 風險管理中的人才培養(yǎng)與發(fā)展試題及答案
- 公司師徒制、導師制管理辦法(完整版方案)
- 解剖學公開課課件內(nèi)分泌
- 家族財富管理
- 高中必修一英語單詞湘教版
- 森林防火預警監(jiān)測
- 銀屑病臨床病例討論
- 涉密人員審查備案登記表
- 園林綠化員工安全培訓
- 蛙泳教學課件教學課件
- 高層建筑汽車吊吊裝作業(yè)方案
- 【初中歷史】大一統(tǒng)王朝的鞏固+課件-2024-2025學年統(tǒng)編版(2024)七年級歷史上
評論
0/150
提交評論