java 恶意代码漏洞 - 字段应受包保护

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16646319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:33:25  来源:igfitidea点击:

Malicious code vulnerability - Field should be package protected

javasonarqube

提问by dumper

Sonar is giving me the message:

声纳给我的信息:

Malicious code vulnerability - Field should be package protected for static array FORMATS.

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

Why is this code considered malicious? I have a public class to store all the constants.

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

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"
}

回答by assylias

Probably because another piece of code could execute:

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

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

And break the rest of your code.

并打破其余的代码。

In other words your array is constant but not its content.

换句话说,您的数组是常量,但不是其内容。

Examples of alternatives:

替代方案示例:

  • you can store each format as a separate String constant
  • you can use an immutable list instead: 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"));
  • make it a method:

    public static String[] formats() {
      return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
    }
    
  • ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.
  • 您可以将每种格式存储为单独的字符串常量
  • 您可以改用不可变列表: 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) 您/您的同事甚至不会考虑重新分配其中一个值,请忽略警告。