Findbugs 有关 Java 中日期对象可变性的问题
正如问题中所述,下面的代码
public Date getSomeDate() {
return someDate;
}
将为您提供 findbug 错误 问题。
建议的解决方案是在 getter 和 setter 中复制 Date 对象,例如
public Date getSomeDate() {
return new Date(someDate.getTime());
}
这是一个好的方法还是有其他方法吗?
java中有没有可用的不可变日期库可以解决这个问题?
This is more of a follow-up to questions 1 & 2.
As told in the questions the below code
public Date getSomeDate() {
return someDate;
}
will give you the findbug error issue.
The suggested solution was to duplicate the Date object in both getters and setters like
public Date getSomeDate() {
return new Date(someDate.getTime());
}
Is this a good approach or are there any alternative ways to this?
Is there any Immutable Date library available in java that can overcome this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,
除了调整 getter 和 setter 之外,您还需要注意空值:
Attention Folks...
besides adapting both the getter and the setter you need to take care about null values:
JodaTime 具有不可变的日期。
当然,在 getter 中使用
Date
构造函数是可以的,为什么不呢?也就是说,仅仅因为 FindBugs 将可变状态标记为潜在错误,并不意味着它本质上值得关注——这取决于类的使用方式。不变性消除了一种类型的错误,您可能需要也可能不需要太关心。
JodaTime has immutable dates.
Sure, it's okay to use a
Date
constructor in a getter, why wouldn't it be?That said, just because FindBugs pegs mutable state as a potential error, it doesn't mean it's intrinsically worth caring about–it depends on how the class is being used. Immutability eliminates one type of bug, which you may or may not need to care a lot about.
根据您的用例,您可以返回
someDate.getTime()
而不将其包装在Date
中。Depending on you use-case you could return
someDate.getTime()
without wrapping it in aDate
.等一下...通过在
getSomeDate
和setSomeDate
方法中复制对象,我们并没有消除安全风险,因为更改的对象通过setSomeDate< 返回/code> 和副本保留更改的值。为了解决这种安全问题,有必要删除
setSomeDate
,或者根本不用担心它。Wait a minute... by copying the object within the
getSomeDate
andsetSomeDate
methods we are not eliminating the security risk since the changed object comes back through thesetSomeDate
and copies preserve the changed values. It would be necessary to removesetSomeDate
in order to solve this kind of security issue, or do not worry at all about it.