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

Cloning a Singleton Object

Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
Hi Guys,

I just wanted to know that is it possible to clone a singleton object ....if yes then y??
If the object is a singleton, then what measures need to be taken so that only single instance of it exists?





Regards,
Alps


Thanks,
Alps
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Don't you think cloning a singleton would defeat the purpose of having a singleton in the first place? Is this a homework question?


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
Well in that case if someone tries cloning a singleton object then.......

In that case i think we should provide a clone method which throws a CloneNotSupportedExcption in our Singleton class....so anyone if at all tries to clone the singleton oject.. would get a exception...and in this way tha object wont be cloned..
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Alpesh Rathod wrote:
In that case i think we should provide a clone method which throws a CloneNotSupportedExcption in our Singleton class....


You do not need to do anything.
From the Cloneable API docs (emphasis added)
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19790
    
  20

You will need to throw an exception if your singleton class extends (directly or indirectly) another class that does implement Cloneable. Throwing a CloneNotSupportedException yourself is a valid solution - just remember to document it.


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: Cloning a Singleton Object