Serializing ENUM Singleton
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 v开发者_StackOverflowoid 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.
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.
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.
精彩评论