Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

clone

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.

But for an java.util.Date there are two common ways to create that copy:

  • clone: (Date) originalDate.clone()
  • copy via constructor new Date(originalDate.getTime())

My question is, which way is better, and why?

like image 657
Ralph Avatar asked Aug 16 '11 17:08

Ralph


People also ask

Is Java Util date cloneable?

Because Date is nonfinal, the clone method is not guaranteed to return an object whose class is java. util. Date; it could return an instance of an untrusted subclass specifically designed for malicious mischief.

How do you copy a date in Java?

The clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object.

Does clone return a deep copy?

clone() when called returns a shallow copy of the object.


2 Answers

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

like image 120
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet


Read Effective Java. The preferred way to create copies is to use the copy constructor approach.

Bill Venners: In your book you recommend using a copy constructor instead of implementing Cloneable and writing clone. Could you elaborate on that?

Josh Bloch: If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.

like image 24
Amir Afghani Avatar answered Oct 12 '22 21:10

Amir Afghani