• Post Reply Bookmark Topic Watch Topic
  • New Topic

Typesafe Enum Pattern (Joshua Bloch)  RSS feed

 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For those of you who don't know about the Typesafe Enum Pattern, a reference is here: http://java.sun.com/developer/Books/effectivejava/Chapter5.pdf (Item 21)
I have used this pattern effectively ever since Joshua Bloch wrote this wonderful book, however, I recently stumbled upon a problem with this pattern, which I'm surprised I haven't stumbled on before.
The Typesafe Enum has no possibility of ever being Serializable, since it demands the removal of the public default constructor (by making it private).
Has anyone stumbled on this problem before ?
If so, are there any decent alternatives ?
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why am I thinking a Serializable requires a public default constructor ?
I don't know why I was thinking that.

// works fine
import java.io.*;
class X implements Serializable
{
private X(){}
public static final X x1 = new X();
}
public class Y
{
public static void main(String[] args) throws IOException
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("blah"));
out.writeObject(X.x1);
out.close();
}
}
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I often find that asking a question helps me to solve it myself
Thanks for posting the link -- I wasn't familiar with that pattern.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to take another look at the Effective Java extract you posted. On page 11, it includes an explanation of making an enum Serializable, which states that a Serializable enum should include a readResolve method, in order to prevent "duplicate constants from coexisting as a result of deserialization".
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Silly me, thanks for pointing that out.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!