Java 中 Date 对象可变性的 Findbugs 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7932489/
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
Findbugs issues with mutability of Date object in Java
提问by ManuPK
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.
会给你 findbug 错误问题。
The suggested solution was to duplicate the Date object in both getters and setters like
建议的解决方案是在 getter 和 setter 中复制 Date 对象,例如
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?
java中是否有任何可以克服这个问题的不可变日期库?
采纳答案by Dave Newton
JodaTimehas immutable dates.
JodaTime具有不可变的日期。
Sure, it's okay to use a Date
constructor in a getter, why wouldn't it be?
当然,Date
在 getter 中使用构造函数是可以的,为什么不呢?
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.
也就是说,仅仅因为 FindBugs 将可变状态视为潜在错误,并不意味着它本质上值得关注——这取决于类的使用方式。不变性消除了一种类型的错误,您可能需要也可能不需要非常关心它。
回答by Martin Bluemel
Attention Folks...
市民注意...
besides adapting both the getter and the setter you need to take care about null values:
除了调整 getter 和 setter 之外,您还需要注意空值:
public Date getSomeDate() {
if (this.someDate == null) {
return null;
}
return new Date(this.someDate.getTime());
}
public void setSomeDate(final Date someDate) {
if (someDate == null) {
this.someDate = null;
} else{
this.someDate = new Date(someDate.getTime());
}
}
回答by Fredrik LS
Depending on you use-case you could return someDate.getTime()
without wrapping it in a Date
.
根据您的用例,您可以返回someDate.getTime()
而不将其包装在Date
.
回答by Hildeberto Mendonca
Wait a minute... by copying the object within the getSomeDate
and setSomeDate
methods we are not eliminating the security risk since the changed object comes back through the setSomeDate
and copies preserve the changed values. It would be necessary to remove setSomeDate
in order to solve this kind of security issue, or do not worry at all about it.
等一下...通过在getSomeDate
和setSomeDate
方法中复制对象,我们并没有消除安全风险,因为更改的对象通过setSomeDate
和 副本保留更改的值。setSomeDate
为了解决这种安全问题,有必要删除,或者根本不用担心。