File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Singleton class 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 class" Watch "Singleton class" New topic
Author

Singleton class

amarkirt saroay
Ranch Hand

Joined: Mar 16, 2008
Posts: 167
Can a singleton class be serializable?


SCJP-75%
SCWCD-82%
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Yes, but it will no longer be a true singleton.

Singleton ---> same object ---> same object ---> same object ---> serialise ---> deserialise ---> different object
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Probably not easy enough a question for beginners. Moving.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

Campbell Ritchie wrote:Yes, but it will no longer be a true singleton.

Singleton ---> same object ---> same object ---> same object ---> serialise ---> deserialise ---> different object

That's what the readResolve and writeReplace are for, especially the former:

But Joshua Bloch has given a very good alternative in his "Effective Java" book: use an enum with only one element:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39393
    
  28
Thank you Rob. I had quite forgotten about readResolve.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton class