天天看点

findbugs自定义检查器

用检查代码中是否存在System.out为例。
package edu.umd.cs.findbugs.detect;

import org.apache.bcel.classfile.Code;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;

/**
 * @author  判断System.out和System.error这种情况
 */
public class ForbiddenSystemClass extends OpcodeStackDetector {
	BugReporter bugReporter;

	public ForbiddenSystemClass(BugReporter bugReporter) {
		this.bugReporter = bugReporter;
	}

	/**
	 * visit方法,在每次进入字节码方法的时候调用 在每次进入新方法的时候清空标志位
	 */
	@Override
	public void visit(Code obj) {
		super.visit(obj);
	}

	/**
	 * 每扫描一条字节码就会进入sawOpcode方法
	 * 
	 * @param seen
	 *            字节码的枚举值
	 */
	@Override
	public void sawOpcode(int seen) {
		// getstatic #57; //Field java/lang/System.out:Ljava/io/PrintStream;
		if (seen == GETSTATIC) {
			if (getClassConstantOperand().equals("java/lang/System")
					&& (getNameConstantOperand().equals("out") || getNameConstantOperand()
							.equals("error"))) {
				BugInstance bug = new BugInstance(this, "CJ_SYSTEMCLASS",
						NORMAL_PRIORITY).addClassAndMethod(this).addSourceLine(
						this, getPC());
				bugReporter.reportBug(bug);
			}
		}


	}
}
           
配置文件 :findbugs.xml
<FindbugsPlugin>
  <Detector class="edu.umd.cs.findbugs.detect.ForbiddenSystemClass"  speed="fast" reports="CJ_SYSTEMCLASS" hidden="false" />
  <BugPattern abbrev="CJ_SYSTEMCLASS" type="CJ_SYSTEMCLASS" category="PERFORMANCE" />
</FindbugsPlugin>
           
配置文件 :message.xml
<?xml version="1.0" encoding="UTF-8"?>
<MessageCollection>
  <Plugin>
    <ShortDescription>Default FindBugs plugin</ShortDescription>
    <Details>
	<![CDATA[
	<p>
	This plugin contains all of the standard FindBugs detectors.
	</p>
	]]>
    </Details>
  </Plugin>
	<Detector class="edu.umd.cs.findbugs.detect.ForbiddenSystemClass">
	   <Details>
		<![CDATA[
		<p>代码不能出现System.out
		<p>请使用log日志形式打印
		]]>
	   </Details>
	</Detector>
	<BugPattern type="CJ_SYSTEMCLASS">
		<ShortDescription>代码不能出现System.out</ShortDescription>
		<LongDescription>{1}代码不能出现System.out,请使用log形式输出</LongDescription>
		<Details>
	  <![CDATA[
		<p>不能使用System.out和System.err,请使用log</p>
	  ]]>
		</Details>
	  </BugPattern>
	<BugCode abbrev="CJ_SYSTEMCLASS">影响性能的输出System.out</BugCode>
</MessageCollection>
           
findbugs自定义检查器

继续阅读