简体   繁体   English

在静态初始化程序中禁止FindBugs警告

[英]Suppress FindBugs warning in static initializer

I have a static initializer where I am creating a new File object. 我有一个静态初始化程序,我在其中创建一个新的File对象。 When I pass in the name to it FindBugs reports a warning due to the hard-coded absolute path. 当我将名称传递给它时,由于硬编码的绝对路径,FindBugs会报告警告。 How can I suppress this warning? 我怎么能压制这个警告?

private static final String fileName = "/tmp/m123.txt";
static {
    if (new File(fileName).exists()) {
        ....
    }
}

You can use ENUM, I use ENUM to eliminate hardcoding of the strings/text both findbugs and pmd doesn't to show errors or warning. 您可以使用ENUM,我使用ENUM来消除字符串/文本的硬编码,两个findbugs和pmd都不会显示错误或警告。

public enum MyFiles {

    FILE_NAME("/kp/kp1/kp2.tx");

    private String value;

    MyFiles(String value){

        this.value = value;

    }

Your fileName is not uppercase, hence pmd would show error of type 1 for the same. 您的fileName不是大写的,因此pmd会显示类型1的错误。 So change it to upper case 所以把它改成大写

private static final String FILE_NAME = "/tmp/m123.txt"

You could move this hard-coded filename to a properties file, or command line argument etc. 您可以将此硬编码文件名移动到属性文件或命令行参数等。

See this page for a tutorial on property files http://www.mkyong.com/java/java-properties-file-examples/ 有关属性文件的教程,请参阅此页面http://www.mkyong.com/java/java-properties-file-examples/

In you want to ignore this warning though as per the page findbugs.sourceforge.net/manual/running.html#commandLineOptions you can use -exclude filterFile.xml 如果您希望忽略此警告,则根据页面findbugs.sourceforge.net/manual/running.html#commandLineOptions,您可以使用-exclude filterFile.xml

Normally I wouldn't advocate refactoring code too much to avoid warnings, but in this case you're stuck because you cannot annotate static initializers. 通常我不会提倡过多地重构代码来避免警告,但是在这种情况下你会因为无法注释静态初始化器而陷入困境。 You can move the code to a static method in another class which you may annotate with SuppressFBWarnings . 您可以将代码移动到另一个类中的静态方法,您可以使用SuppressFBWarnings注释。

public class MainClass {
    private static final String FILE_NAME = "/tmp/m123.txt";

    static {
        HelperClass.loadFile(FILE_NAME);
    }
}

public class HelperClass {
    @SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
    public static void loadFile(String fileName) {
        if (new File(fileName).exists()) {
            ....
        }
    }
}

Extracting the code may actually be enough to avoid the warning, but I've never encountered this warning before. 提取代码实际上可能足以避免警告,但我以前从未遇到过此警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM