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.
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.