可变字段不应为“公共静态”

时间:2018-12-13 15:07:14

标签: java arrays collections sonarqube

我收到以下行的sonarQube错误,任何建议专家如何解决此问题?预先感谢

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

2 个答案:

答案 0 :(得分:3)

您可以将此数组更改为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));
}

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

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

答案 1 :(得分:2)

您可以将COLUMN_NAMES设为私有,并只需返回其克隆,如下所示:

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

protected static String[] getCloneArray()
{
  return COLUMN_NAMES.clone();
}

这样,您的原始数组将不会被修改。