在findbugs中添加自定义检测器

Man*_*noj 5 java findbugs

我正在尝试添加一个检测器,它将检测System.out.println()的发生.正如在解释这个帖子,我已经写了检测类,findbugs.xml文件和messages.xml文件.我创建了一个包含我的探测器类,findbugs.xml和messages.xml文件的jar.我在我的eclipse环境中添加了这个jar(window-> preferences-> java-> findbugs-> Plugins和misc.Settings).但它显示无效输入.

探测器类:

    package findbugs.custom.detector;
    import edu.umd.cs.findbugs.BugInstance;
    import edu.umd.cs.findbugs.BugReporter;
    import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
    import edu.umd.cs.findbugs.classfile.ClassDescriptor;
    import edu.umd.cs.findbugs.classfile.FieldDescriptor;
    public class CallToSystemOutPrintlnDetector2 extends OpcodeStackDetector {


private BugReporter bugReporter;


public CallToSystemOutPrintlnDetector2(BugReporter bugReporter) {
    super();
    this.bugReporter = bugReporter;

}


public void sawOpcode(int seen) {
    if (seen == GETSTATIC){

        try {
            FieldDescriptor operand = getFieldDescriptorOperand();
            ClassDescriptor classDescriptor = operand.getClassDescriptor();
            if ("java/lang/System".equals(classDescriptor.getClassName()) && 
                    ("err".equals(operand.getName())||"out".equals(operand.getName()))) {
                reportBug();
            }
        } catch (Exception e) {
            //ignore
        }
    }
}

private void reportBug(){
    this.bugReporter.reportBug(getBugInstance());
}


private BugInstance getBugInstance() {
    return new BugInstance(this, "MY_CALL_TO_SYSTEM_OUT_BUG", 10)
        .addClassAndMethod(this)
        .addSourceLine(this);
}
}
Run Code Online (Sandbox Code Playgroud)

findbugs.xml文件:

    <FindbugsPlugin>
    <Detector class="findbugs.custom.detector.CallToSystemOutPrintlnDetector2" speed="fast" />
    <BugPattern abbrev="SYS_OUT_P" type="CALL_TO_SYSTEM_OUT" category="CORRECTNESS" />
    </FindbugsPlugin>
Run Code Online (Sandbox Code Playgroud)

messages.xml文件:

    <MessageCollection>
    <Detector class="findbugs.custom.detector.CallToSystemOutPrintlnDetector2">
    <Details>
    <![CDATA[
    <p>This detector warns about SYS_OUTs used in the code. It is a fast detector.</p>
    ]]>
    </Details>
    </Detector>
    <BugPattern type="CALL_TO_SYSTEM_OUT_BUG">
    <ShortDescription>sysout detector</ShortDescription>
    <LongDescription>Found sysout in {1}</LongDescription>
    <Details>
    <![CDATA[
    <p>This is a call to System.out.println/err method. </p>
    which should be avoided.
    ]]>
    </Details>
    </BugPattern>
    <BugCode abbrev="SYS_OUT_P">Found sysout</BugCode>
    </MessageCollection>
Run Code Online (Sandbox Code Playgroud)

我怎么能纠正这个?

Man*_*noj 1

该错误是由于包层次结构造成的。我的检测器类位于findbugs.custom.detector包内,但是当我创建 jar 时(使用 eclipse),我只选择所需的文件(findbugs.xml、messages.xml、检测器类)。因此,jar 中不包含包信息。我们的 XML 文件使用值为 的标签class属性读取检测器类。因此,当 XML 文件尝试读取检测器类时,它们无法找到package.json 文件。要构建包含包信息的 jar,请选择整个项目,然后创建包含所需文件的 jar。Detectorfindbugs.custom.detector.MyDetectorClassfindbugs.custom.detector