views:

171

answers:

2

I'm trying to serialize an ENUM singleton instance (as described by Joshua Bloch in his book Effective Java) to a file. The ENUM instance is a simple JavaBean as this:

public enum ElvisFan implements Serializable{
  INSTANCE;
  private int totalSongsListened;

private ElvisFan(){
     totalSongsListened=0;
}

public void set(int v){
     totalSongsListened=v;
}

public int get(){
     return totalSongsListened;
}

}
}

I'm successfully using this enum all over my program but when I write this enum to a file using snakeyaml, I just have !!com.chown.ElvisFan 'INSTANCE' in my test.yaml file. This is what I'm doing:

Yaml yaml = new Yaml();
yaml.dump(ElvisFan.INSTANCE, new FileWriter("test.yml");

I also tried this without any luck:

JavaBeanDumper dumper = new JavaBeanDumper();
dumper.dump(ElvisFan.INSTANCE, new FileWriter("test.yml");

Can someone please guide me on this. Thanks!

[Edited]

Code correction.

+3  A: 

Singletons don't reakky make any sense. Serialisable singletons make even less sense. There is by definition only one singleton. So when you deserialise a singleton you are not going to get a new object. You will get the same old instance with the same old data.

Enums serialisation is handled specially. They are represented by name and type. No other state is saved, because as previously stated that doesn't make any sense.

I suggest modifying your code to avoid mutable statics.

Enums should not have mutable state. Serialising enums with a single instance can make sense where they implement some other class, such as Comparator, or are use as a key or somesuch.

Tom Hawtin - tackline
that's what i need to attain - same old data and the same old instance. I'm pretty much sure the data can be saved because snakeyaml documentation provides a similar example on dumping/loading enum data: http://code.google.com/p/snakeyaml/wiki/Documentation#Enum
chown
Which old instance? The old instance that exists, or the old "instance" that doesn't really exist in serialised form.
Tom Hawtin - tackline
A: 

SnakeYAML treats a List as a sequence not as a mapping even though List has also getters (getFirst()). Why do you expect enum to be serialized as map ?

You have to provide a custom Representer to dump such an unusual enum as a JavaBean. Tests contain a lot of examples how to write a custom Representer/Constructor.