




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
FindBugs常見(jiàn)問(wèn)題指南1
ComparisonofStringobjectsusing==or!=例,overrideequals方法時(shí)容易犯錯(cuò)Java代碼
\o"收藏這段代碼"if(this.topic
!=
key.getTopic())
return
false;2DeadstoretonewStatusRecord
定義局部變量后沒(méi)有引用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()
忽略了返回值,應(yīng)當(dāng)含有返回值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();
應(yīng)當(dāng)
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);
//
可能會(huì)傳入空引用
//...
}
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);
//
可能會(huì)傳入空引用
//...
}
long
countIpAddress(String
ip)
{
long
ipNum
=
0;
if
(ip
==
null)
{
return
0;
//或者拋出異常
}
String[]
ipArray
=
ip.split("\\.");
//...
}
注意:函數(shù)入口需要交驗(yàn)入?yún)⒌暮戏ㄐ浴?3Methodconcatenatesstringsusing+inaloop
在循環(huán)里使用字符串連接,效率低,應(yīng)該使用StringBuilder/StringBuffer
例:
Java代碼
\o"收藏這段代碼"String
writeData
=
"";
for
(int
i
=
0;
i
<
10;
i++)
{
writeData
=
writeData
+
"a";
}
14Methodmayfailtoclosedatabaseresource
沒(méi)有釋放數(shù)據(jù)庫(kù)資源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;
}
應(yīng)當(dāng)修改為:
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
沒(méi)有關(guān)閉流,可能會(huì)導(dǎo)致文件描述符泄露,應(yīng)該在finally中關(guān)閉
例: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.應(yīng)該將異常處理、打印或者拋出反例:Java代碼
\o"收藏這段代碼"try
{
//...
}
catch
(Exception
e)
{
}
17Classdefinesnon-transientnon-serializableinstancefieldreaderTypeInfo
一個(gè)實(shí)現(xiàn)了Serializable接口的類,含有非transient和非serializable的實(shí)例對(duì)象域。
ThisSerializableclassdefinesanon-primitiveinstancefieldwhichisneithertransient,Serializable,orjava.lang.Object,anddoesnotappeartoimplementtheExternalizableinterfaceorthereadObject()andwriteObject()methods.
Objectsofthisclasswillnotbedeserializedcorrectlyifanon-Serializableobjectisstoredinthisfield.18Nullcheckofvaluepreviouslydereferenced
前面獲取的對(duì)象,現(xiàn)在引用的時(shí)候沒(méi)有交驗(yà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());
//
使用前沒(méi)有做null校驗(yàn)
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引用前需要做空校驗(yàn)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)部類沒(méi)有引用外部類的屬性/方法的時(shí)候,應(yīng)該作為靜態(tài)內(nèi)部類。Thisclassisaninnerclass,butdoesnotuseitsembeddedreferencetotheobjectwhichcreatedit.
Thisreferencemakestheinstancesoftheclasslarger,andmaykeepthereferencetothecreatorobjectalivelongerthannecessary.
Ifpossible,theclassshouldbemadestatic.
23包裝類的比較應(yīng)該使用eueqls,要比較值類型,需要強(qiáng)制類型轉(zhuǎn)換后再使用。Thismethodcomparestworeferencevaluesusingthe==
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 公路建設(shè)項(xiàng)目借款合同范例
- 會(huì)計(jì)師職稱考試的課程安排試題及答案
- 公司大樓轉(zhuǎn)讓合同范例
- 優(yōu)思家教合同范例
- 基礎(chǔ)知識(shí)在無(wú)人機(jī)駕駛員執(zhí)照考試中的重要性與試題答案
- 二手車位買賣合同范例
- 全款安置房合同范例
- 五菱榮光轉(zhuǎn)讓合同范例
- 倉(cāng)儲(chǔ)臨時(shí)加工合同范例
- 臨夏彩陶買賣合同范例
- 2025年全國(guó)保密教育線上培訓(xùn)考試試題庫(kù)及答案【網(wǎng)校專用】含答案詳解
- 華為管理面試題及答案
- 初中2年級(jí)家長(zhǎng)會(huì)課件
- 2024-2025學(xué)年統(tǒng)編版小學(xué)道德與法治三年級(jí)下冊(cè)期中考試測(cè)試卷附答案
- 智能垃圾桶設(shè)計(jì)方案資料
- 2025陜西漢中漢源電力(集團(tuán))限公司招聘56人易考易錯(cuò)模擬試題(共500題)試卷后附參考答案
- 2025年北京市西城區(qū)中考一模道德與法治試卷(含答案)
- 新聞報(bào)道的寫作及范例課件
- 危重病人的搶救與配合 2
- 2025-2030中國(guó)CAD-CAM牙科系統(tǒng)行業(yè)市場(chǎng)發(fā)展趨勢(shì)與前景展望戰(zhàn)略研究報(bào)告
- 【9數(shù)一?!?025年安徽省合肥市第四十五中學(xué)九年級(jí)中考數(shù)學(xué)一模試卷
評(píng)論
0/150
提交評(píng)論