1、FindBugs使用手册FindBugs使用手册文件编号:配置项编号:FindBugs使用手册文档版本号V1.0农信银资金清算中心创新研发部未经农信银资金清算中心的书面许可,不得翻印或外传 -1/10-编号章节名称修订内容简述修订日期版本号修订人批准人1创建FindBugs使用手册2011-07-12V1.0李远卓FindBugs使用手册未经农信银资金清算中心的书面许可,不得翻印或外传 -2/10-FindBugs使用手册1、 FindBugs简介.42、FindBugs的检查规则. 42.1 Correctness(正确性).42.2 Badpractice(不良实践).52.3 Perfo
2、rmance(性能).52.4 Multithreadedcorrectness(多线程正确性).62.5 Dodgy(不可靠).73、FindBugs使用. 83.1 安装FindBugs.83.2 配置FindBugs.83.3 使用FindBugs.8未经农信银资金清算中心的书面许可,不得翻印或外传 -3/10-FindBugs使用手册1、FindBugs简介FindBugs是用于java代码检查的一种静态分析工具,它检查类或者JAR文件,将字节码与一组缺陷模式进行对比以发现可能的问题。有了静态分析工具,就可以在不实际运行程序的情况对软件进行分析。FindBugs专注于找出潜在程序错误,
3、而不是编码风格问题,目的在于提高程序的健壮性。2、FindBugs的检查规则FindBugs提出了超过200种规则,这些规则可主要分为如下类别:2.1Correctness(正确性)这些问题涉及到可能在某些方面不正确的代码。如:代码有无限递归,或者读取为写入的字段,这类问题几乎无疑是程序的错误。例1:使用未初始化的类成员,可能导致NullPointException代码:publicclassFindBugsTestprivateListitems;publicvoidaddItem(Stringitem)items.add(item);FindBugs检测结果:Bug:Readofunwri
4、ttenfielditemsPatternid:NP_UNWRITTEN_FIELD,type:NP,category:CORRECTNESSTheprogramisdereferencingafieldthatdoesnotseemtoeverhaveanon-nullvaluewrittentoit.Dereferencingthisvaluewillgenerateanullpointerexception.例2:不使用方法的返回值代码:StringaString=bob;aString.replace(b,p);FindBugs检测结果:Bug:com.nxy.test.FindBug
5、sTest.testString()ignoresreturnvalueofString.replace(char,char)Patternid:RV_RETURN_VALUE_IGNORED,type:RV,category:CORRECTNESS未经农信银资金清算中心的书面许可,不得翻印或外传 -4/10-FindBugs使用手册Thereturnvalueofthismethodshouldbechecked.Onecommoncauseofthiswarningistoinvokeamethodonanimmutableobject,thinkingthatitupdatestheob
6、ject.Forexample,inthefollowingcodefragment,StringdateString=getHeaderField(name);dateString.trim();theprogrammerseemstobethinkingthatthetrim()methodwillupdatetheStringreferencedbydateString.ButsinceStringsareimmutable,thetrim()functionreturnsanewStringvalue,whichisbeingignoredhere.Thecodeshouldbecor
7、rectedto:StringdateString=getHeaderField(name);dateString=dateString.trim();2.2Badpractice(不良实践)这类问题明确违反建议的编程标准。如:删除异常,或未关闭文件,或未数据库连接资源等。例3:未关闭打开的文件输出流资源代码:publicvoidtestFileNotClosed()tryFileOutputStreamfos=newFileOutputStream(D:test.txt);fos.write(0);catch(FileNotFoundExceptione)e.printStackTrace(
8、);catch(IOExceptione)e.printStackTrace();FindBugs检测结果:Bug:com.nxy.test.FindBugsTest.testFileNotClosed()mayfailtoclosestreamPatternid:OS_OPEN_STREAM,type:OS,category:BAD_PRACTICEThemethodcreatesanIOstreamobject,doesnotassignittoanyfields,passittoothermethodsthatmightcloseit,orreturnit,anddoesnotappea
9、rtoclosethestreamonallpathsoutofthemethod. Thismayresultinafiledescriptorleak. Itisgenerallyagoodideatouseafinallyblocktoensurethatstreamsareclosed.未经农信银资金清算中心的书面许可,不得翻印或外传 -5/10-FindBugs使用手册2.3Performance(性能)这类规则的目的在于检测潜在的性能问题。如:代码创建了不需要的对象,或者在循环中使用字符串连接而不是使用StringBuffer。例4:使用newString(String)构造函数创
10、建字符串代码:Stringstr=newString(string);FindBugs检测结果:Bug:com.nxy.test.FindBugsTbineString()invokesinefficientnewString(String)constructorPatternid:DM_STRING_CTOR,type:Dm,category:PERFORMANCEUsingthejava.lang.String(String)constructorwastesmemorybecausetheobjectsoconstructedwillbefunctionallyindistinguish
11、ablefromtheStringpassedasaparameter. JustusetheargumentStringdirectly.2.4Multithreadedcorrectness(多线程正确性)这是一类特殊的问题,涉及到同步和多线程代码有关的问题。例5:在构造方法中start线程代码:publicFindBugsTest()Threadthread=newThread();thread.start();FindBugs检测结果:Bug:newcom.nxy.test.FindBugsTest()invokesThread.start()Patternid:SC_START_IN
12、_CTOR,type:SC,category:MT_CORRECTNESSTheconstructorstartsathread.Thisislikelytobewrongiftheclassiseverextended/subclassed,sincethethreadwillbestartedbeforethesubclassconstructorisstarted.例6:同一成员变量的getter和setter方法的同步性不统一代码:privateStringname;publicsynchronizedStringgetName()returnname;未经农信银资金清算中心的书面许可
13、,不得翻印或外传 -6/10-FindBugs使用手册publicvoidsetName(Stringname)this.name=name;FindBugs检测结果:Bug:Inconsistentsynchronizationofcom.nxy.test.FindBugsTest.name;locked50%oftimePatternid:IS2_INCONSISTENT_SYNC,type:IS,category:MT_CORRECTNESSThefieldsofthisclassappeartobeaccessedinconsistentlywithrespecttosynchroni
14、zation. Thisbugreportindicatesthatthebugpatterndetectorjudgedthat1、Theclasscontainsamixoflockedandunlockedaccesses,2、Atleastonelockedaccesswasperformedbyoneoftheclasssownmethods,and3、Thenumberofunsynchronizedfieldaccesses(readsandwrites)wasnomorethanonethirdofallaccesses,withwritesbeingweighedtwicea
15、shighasreadsAtypicalbugmatchingthisbugpatternisforgettingtosynchronizeoneofthemethodsinaclassthatisintendedtobethread-safe.YoucanselectthenodeslabeledUnsynchronizedaccesstoshowthecodelocationswherethedetectorbelievedthatafieldwasaccessedwithoutsynchronization.Notethattherearevarioussourcesofinaccura
16、cyinthisdetector;forexample,thedetectorcannotstaticallydetectallsituationsinwhichalockisheld. Also,evenwhenthedetectorisaccurateindistinguishinglockedvs.unlockedaccesses,thecodeinquestionmaystillbecorrect.2.5Dodgy(不可靠)这类问题涉及奇怪的代码。如:未使用的本地变量或未检查的类型转换(cast)。例7:定义了未被使用的变量代码:Personperson=(Person)aMap.ge
17、t(bob);Stringname=person.getName();/后续代码不曾使用过本地变量name.FindBugs检测结果:未经农信银资金清算中心的书面许可,不得翻印或外传 -7/10-FindBugs使用手册Bug:DeadstoretonamePatternid:DLS_DEAD_LOCAL_STORE,type:DLS,category:STYLEThisinstructionassignsavaluetoalocalvariable,butthevalueisnotreadorusedinanysubsequentinstruction.Often,thisindicates
18、anerror,becausethevaluecomputedisneverused.NotethatSunsjavaccompileroftengeneratesdeadstoresforfinallocalvariables.BecauseFindBugsisabytecode-basedtool,thereisnoeasywaytoeliminatethesefalsepositives.3、FindBugs使用3.1安装FindBugs可以以多种方式运行FindBugs从GUI、从命令行、使用Ant、作为Eclipse插件程序和使用Maven。这里重点介绍FindBugs作为Eclip
19、se插件程序的使用方法。从internet上下载FindBugs的eclipseplugin压缩包;将plugin解压至$ECLIPSE_ROOT$/plugins路径下,重启eclipse3.2配置FindBugs进入如下目录:ProjectProperties,如下图所示:说明:选中EnableProjectspecificsettings为特定的项目详细配置FindBugs。选中Runautomatically,在每次对类进行修改后,FindBugs将自动检查问题。Detector details项会给出被选中Detector的相信说明,包括该Detector的检测规则,所属模式等信息。
20、ReporterConfiguration定义了报告错误的级别,默认情况分别为Medium,同时定义了错误类别,默认情况下为前面所列的几种主要类别。未经农信银资金清算中心的书面许可,不得翻印或外传 -8/10-FindBugs使用手册3.3使用FindBugs点击OK,FindBugs开始运行:可以通过Problems(问题)视图查看FindBugs的检查结果,在该视图中,FindBugs检测出来的问题和其他错误和警告一起列出。要查看某个FindBugs检查结果的详细信息,使用如下方法:在源代码中点击“红色小虫”标记,将在Properties(属性)视图中显示出该问题的详细信息。如下图所示:未
21、经农信银资金清算中心的书面许可,不得翻印或外传 -9/10-FindBugs使用手册使用Filter选择地禁用规则可以有不同的方式定义过滤器:匹配一个类的过滤器。可以用这些过滤器忽略在特定类中发现的所有问题。匹配一个类中特定缺陷代码(bugcode)的 过滤器。可以用这些过滤器忽略在特定类中发现的一些缺陷。匹配一组缺陷的过滤器。可以用这些过滤器忽略所分析的所有类中的一组缺陷。匹配所分析的一个类中的某些方法的过滤器。可以用这些过滤器忽略在一个类中的一组方法中发现的所有缺陷。匹配在所分析的一个类中的方法中发现的某些缺陷的过滤器。可以用这些过滤器忽略在一组方法中发现的特定缺陷。未经农信银资金清算中心的书面许可,不得翻印或外传 -10/10-