这类文章极少,字节码操作需要对becl库及jvm字节码操作有一定常识。参考:
http://blog.csdn.net/lywybo/archive/2010/03/01/5335748.aspx
ibm介绍的原理实用,但配置过时;支付宝朋友写的message.xml/findbugs.xml不够详细且有笔误。
1.1准备
修改build.xml ,去除所有的validate依赖。执行ant编译。
eclipse引入findbugs工程。
1.2实现类
直接在findbugs目录中增加类
packageedu.umd.cs.findbugs.detect;
importorg.apache.bcel.classfile.Code;
importedu.umd.cs.findbugs.BugInstance;
importedu.umd.cs.findbugs.BugReporter;
importedu.umd.cs.findbugs.bcel.OpcodeStackDetector;
/**
*@authorbo
*这个规则类用于判断System.out和System.error这种情况
*/
publicclassForbiddenSystemClassextendsOpcodeStackDetector{
BugReporterbugReporter;
publicForbiddenSystemClass(BugReporter bugReporter) {
this.bugReporter= bugReporter;
}
/**
* visit方法,在每次进入字节码方法的时候调用
*在每次进入新方法的时候清空标志位
*/
@Override
publicvoidvisit(Code obj) {
super.visit(obj);
}
/**
*每扫描一条字节码就会进入sawOpcode方法
*
*@paramseen字节码的枚举值
*/
@Override
publicvoidsawOpcode(intseen) {
if(seen ==GETSTATIC) {
if(getClassConstantOperand().equals("java/lang/System")
&& (getNameConstantOperand().equals("out") || getNameConstantOperand().equals("error"))) {
BugInstance bug =newBugInstance(this,"ALP_SYSTEMCLASS",NORMAL_PRIORITY).addClassAndMethod(this)
.addSourceLine(this, getPC());
bug.addInt(getPC());
bugReporter.reportBug(bug);
}
}
}
}
1.3修改etc目录配置文件findbugs.xml和message.xml
不支持中文注释。
在findbugs.xml增加内容。
speed="fast"
reports="ALP_SYSTEMCLASS"
hidden="false"/>
Message.xml增加:
category:detector find System.out/System.error
please use log4j
]]>
short desc:System.out/error
class={0},method {1}long desc:System.out,please use log4j
detail info see log4j document
]]>
1.4用findbugs
点击bin/finbugs.bat,打开扫描的.class目录。看到扫描带System.out或者System.error的.class放到experimental类错误时,验证成功。
1.5替换eclipse findbugs-plugin.jar文件
用winrar打开
D:\devtools\eclipse_3.5.1\plugins\edu.umd.cs.findbugs.plugin.eclipse_1.3.9.20090821\findbugs-plugin.jar中message.xml,findbugs.xml,z加入二进制的edu.umd.cs.findbugs.detect.ForbiddenSystemClass。
重启elipse,还需要确保experimental类的错误能在findbugs窗口展现:windows->preferences->java->findbugs->reporter configuration上的experimental选项勾上。
执行findbugs扫描.class,看到结果出现..