5

声纳给我的信息是:

恶意代码漏洞 - 字段应针对静态数组进行包保护FORMATS

为什么这段代码被认为是恶意的?我有一个公共类来存储所有常量。

public class Constants
{
    /*
    all the public static final constants of primitive datatypes for which 
    there is no sonar warning.
    */
    public static final String[] FORMATS = new String[] {
        "yyyy-MM-dd HH:mm:ss.S z", 
        "yyyy-MM-dd HH:mm:ss.S"
}
4

1 回答 1

20

可能是因为另一段代码可以执行:

Constants.FORMATS[0] = "SOME GARBAGE";

并打破你的其余代码。

换句话说,您的数组是恒定的,但不是它的内容。

替代品示例:

  • 您可以将每种格式存储为单独的字符串常量
  • 您可以改用不可变列表:public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));
  • 使它成为一种方法:

    public static String[] formats() {
      return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
    }
    
  • 如果您确信 (i) 只有您自己的代码可以访问该类并且 (ii) 您/您的同事甚至不会考虑重新分配其中一个值,请忽略该警告。
于 2013-05-20T09:24:45.833 回答