Sonar - 将 DATE_FORMAT 作为实例变量

Sonar - Make DATE_FORMAT as instance variable

我有一个休息网络服务,下面是我声明 DateFormat 的方式,因为这是我将在应用程序范围内使用的日期格式。

当我使用 SonarLint eclipse 插件进行代码分析时,我收到了严重的警告 "Make DATE_FORMAT as instance variable."

public class Constants {

    private Constants() {

    }

    public static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS");

}

任何人都可以告诉我如果我在休息时以这种方式使用它可能会遇到什么问题 API 吗?
如果我将它用作实例变量,我最终会在多个 类 中声明它?

静态变量主要用于常量。
在这里你已经声明了 static 并为其分配了 SimpleDateFormat.
的实例 要么使 DATE_TIME_FORMAT 成为非静态的,要么为该变量分配一个常量。

最好将其更改为实例变量并使用 Sting 来完成。
例如 public final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SSS";

使用 joda-time 或简单地用方法替换变量:

public static final DateFormat getDateTimeFormat() {
    return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS");
}

触发规则为S2885:

Non-thread-safe fields should not be static

squid:S2885

Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime. This rule raises an issue when an instance of Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.

由于 SimpleDateFormat 不是线程安全的,它不能很好地在线程之间共享。您很可能会以错误的日期格式结束。

如果您使用 Java 8 或更高版本,您应该使用 DateTimeFormatter,如 this answer. Otherwise, using Joda Time makes sence, as per this answer.


作为旁注,将 class 命名为 Constants end 让它包含各种静态最终变量很少有意义。通常你应该把每个常量放在它所属的地方。