Findbugs Java中的Date对象的可变性问题 [英] Findbugs issues with mutability of Date object in Java

查看:886
本文介绍了Findbugs Java中的Date对象的可变性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更多是对 1 & 2



在问题中已经告诉下面的代码

  public Date getSomeDate(){
return someDate;
}

会给你findbug错误问题



建议的解决方案是在getter和setter中复制Date对象, p>

  public Date getSomeDate(){
return new Date(someDate.getTime());这是一个很好的方法,或者有其他方法吗? p>

有没有任何不可变的日期库可以在java中解决这个问题?

解决方案

JodaTime 具有不可更改的日期。



当然,可以在getter中使用 Date 构造函数,为什么不是?



这就是说,只是因为FindBugs把可变状态作为一个潜在的错误,这并不意味着它本质上值得关心–这取决于如何使用类。不变性消除了一种类型的错误,你可能需要或可能不需要太多关注。


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?

解决方案

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.

这篇关于Findbugs Java中的Date对象的可变性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆