问题描述
我有一个Java类:
class MyObj{
private Timestamp myDate;
public Timestamp getMyDate(){
return mydate;
}
...
}
当我通过Findbugs检查它时,它说:
when I check it by Findbugs, it says:
那么,用Java为Date
和Timestamp
类型编写getter
的更好方法是什么?
so, what is the better way to write the getter
for Date
and Timestamp
types in Java?
推荐答案
Date
和Timestamp
都是可变的,因此返回对Timestamp
的引用意味着调用者可以更改类的内部状态.如果有问题,那只有一个问题,如果有道理的话.如果您表示,让调用者能够修改对象的状态(通过修改您要返回的实例字段的状态),就可以了,尽管它可能是相对细微的来源错误.但是,通常,您并不是故意不允许调用者执行此操作.因此,FindBugs对其进行了标记.
Date
and Timestamp
are both mutable, so returning a reference to your Timestamp
means the caller can change the internal state of your class. That's only a problem if it's a problem, if that makes sense; if you mean for the caller to be able to modify the state of your object (by modifying the state of the instance field you're returning), that's okay, though it can be the source of relatively subtle bugs. Often, though, you don't mean to allow the caller to do that; hence FindBugs flagging it up.
如果要避免暴露对可变对象的引用,可以有两种选择:
You have a couple of choices if you want to avoid exposing a reference to a mutable object:
-
在返回对象时将其克隆(防御性副本"),以便调用者获得一个副本,而不是原始副本:
Clone the object when returning it (a "defensive copy"), so that the caller gets a copy, not the original:
public Timestamp getMyDate(){
return new Timestamp(mydate.getTime());
}
返回一个不可变的类型或基元,而不是可变的类型,例如:
Return an immutable type or a primitive instead of a mutable one, for instance:
public long getMyDate(){
return mydate.getTime();
}
根本不使用可变对象.例如,可以使用LocalDateTime或ZonedDateTime
代替Timestamp
.html"rel =" nofollow noreferrer> java.time
,例如:
Don't use a mutable object at all. For instance, instead of Timestamp
, you might use LocalDateTime
or ZonedDateTime
from java.time
, e.g.:
class MyObj{
private LocalDateTime myDate;
public LocalDateTime getMyDate(){
return mydate;
}
// ...
}
如果您需要更新班级中的日期(让我们以添加一天的示例为例),则无需更改对象,而是将其替换为新的对象:
If you need to update the date in your class (let's use the example of adding a day), instead of mutating the object, you replace it with a new one:
this.mydate = this.myDate.plusDays(1);
这篇关于使用Java中的getter函数返回可变成员变量(日期/时间戳)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!