问题描述
最佳做法是不公开Object(Entity)的内部引用。因此,如果一个Object有一个 java.util.Date
类型的字段,那么例如该字段的getter应该不是原始日期而是它的副本。
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 getter for this field should return not the original date but an copy of it.
但对于java.util.Date,有两种常用方法可以创建该副本:
But for an java.util.Date there are two common ways to create that copy:
- clone:
(Date)originalDate.clone()
- 通过构造函数复制
new日期(originalDate.getTime())
- clone:
(Date) originalDate.clone()
- copy via constructor
new Date(originalDate.getTime())
我的问题是,哪种方式更好,为什么?
My question is, which way is better, and why?
推荐答案
如果它肯定只是一个日期
,它将无法生成任何区别。
If it's definitely just a Date
, it won't make any difference either way.
如果实际对象可能是子类 日期
(例如 java.sql.Date
)然后我希望 clone()
会保留额外的信息(包括它是哪个类)而调用构造函数则不会。
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.
顺便说一下,如果你使用了你不会遇到这个问题,因为有很多不可变类型可供使用。它也是一个更好的API:)
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 :)
这篇关于java.util.Date克隆或复制到不公开内部引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!