java getter了函数,使用Java中的getter函数返回可变成员变量(日期/时间戳)?

I have a java class:

class MyObj{

private Timestamp myDate;

public Timestamp getMyDate(){

return mydate;

}

...

}

when I check it by Findbugs, it says:

Bug kind and pattern: EI - EI_EXPOSE_REP May expose internal representation by returning reference to mutable object

so, what is the better way to write the getter for Date and Timestamp types in Java?

解决方案

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();

}

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值