java.util.Date clone or copy to not expose internal reference

前端 未结 3 930
小鲜肉
小鲜肉 2020-12-02 12:03

It is best practice not to expose the internal references of an Object (Entity). So if an Object has a field of type java.util.Date then for example the get

3条回答
  •  被撕碎了的回忆
    2020-12-02 12:33

    If it's definitely just a Date, it won't make any difference either way.

    If the actual object might be a subclass of Date (such as java.sql.Date) then I'd hope that clone() would preserve the extra information (including which class it is) whereas calling the constructor wouldn't.

    As an aside, if you used Joda Time you wouldn't have this problem, as there are plenty of immutable types to use. It's also a much better API :)

提交回复
热议问题