Question
Is a custom enum with non-serializable members Serializable in Java?
public enum Country {
Australia(R.drawable.flag_au),
Austria(R.drawable.flag_at),
UnitedState(R.drawable.flag_us);
Country(int icon) {
this.icon = icon;
nonSerializableClass = new NonSerializableClass(this.toString());
}
public int getIcon() {
return icon;
}
public static class NonSerializableClass {
public NonSerializableClass(String dummy) { this.dummy = dummy; }
public String dummy;
}
private final int icon;
public NonSerializableClass nonSerializableClass;
}
Answer
In Java, all enums are inherently serializable since they implement the Serializable interface. However, when you add non-serializable members to your custom enums, you need to handle serialization carefully to maintain data integrity during the serialization and deserialization processes.
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // Serialize default fields
out.writeInt(icon); // Serialize icon
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // Deserialize default fields
icon = in.readInt(); // Deserialize icon
nonSerializableClass = new NonSerializableClass(this.toString()); // Recreate non-serializable member
}
Causes
- Enums in Java implicitly implement Serializable, allowing standard usage without additional code for simple enums.
- Adding non-serializable member variables means the serializable state of your enum needs to be managed manually to avoid exceptions during serialization.
Solutions
- Implement custom serialization methods like writeObject and readObject in your enum class to control how enum data is serialized and deserialized.
- Mark the non-serializable member variables as transient if they do not need to be serialized and re-constructed post-deserialization.
Common Mistakes
Mistake: Not handling non-serializable members when customizing serialization.
Solution: Implement custom readObject and writeObject methods to ensure that all member variables are correctly serialized.
Mistake: Assuming default serialization will work with non-serializable member variables.
Solution: Always check and implement custom serialization when non-serializable types are present.
Helpers
- Java enums
- Serializable enum
- custom enums serialization
- Java serialization example
- Java enum non-serializable member