可变字段不应该是"公共静态"

Jay*_*Jay 5 java arrays collections sonarqube

我收到sonarQube错误的下线,任何建议专家如何解决这个问题?提前致谢

    protected static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
            "account","emailAdress","mobilePhoneNumber","emailStatus"};
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 9

您可以将此数组更改为private变量。

然后添加一个static返回此数组副本的方法,或List此数组支持的不可变对象。

例如:

private static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
        "account","emailAdress","mobilePhoneNumber","emailStatus"};

protected static List<String> getColumnNames() {
    return Collections.unmodifiableList(Arrays.asList(COLUMN_NAMES));
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以用不可修改的变量代替数组变量,List而不是使用该方法。这会更有效(因为List将创建一次而不是在每次调用static方法时创建):

protected static List<String> COLUMN_NAMES = Collections.unmodifiableList(Arrays.asList("date","customerNumber","customerName",
        "account","emailAdress","mobilePhoneNumber","emailStatus"));
Run Code Online (Sandbox Code Playgroud)

  • 自 JavaSE 9 以来的“List.of”。 (4认同)