aspose file tools*
The moose likes Java in General and the fly likes singleton with clonable and deserialization?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "singleton with clonable and deserialization??" Watch "singleton with clonable and deserialization??" New topic
Author

singleton with clonable and deserialization??

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1281

what happen with singleton contract when singleton object is get cloned or deserialized in both the cases new object has been created...?

Kaustubh


No Kaustubh No Fun, Know Kaustubh Know Fun..
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

what is your opinion regarding this?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

Kaustubh G Sharma wrote:in both the cases new object has been created...?

It depends.

The contract for Object.clone() specifically says that x.clone() == x is allowed, so if your singleton class needs to be Cloneable* you override clone() to return "this".

As for Serializable, if a singleton needs to be Serializable** then you should use the readResolve method. Look it up if you're not familiar with it.

Both will lead to the singleton object being used instead of a new object being created.


* and it usually shouldn't be. The only reason I can think of is when you are sub classing a Cloneable class.
** again, it usually shouldn't be. Again it should only be used if you are sub classing a Serializable class.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton with clonable and deserialization??