I'm currently using JAVA's built in serializer java.io.Serializable
and can't seem to get it to deserialize and set my fields to their default values. I've even attempted to use readObject
to initialize the fields but it just doesn't work.
Here is my code:
public abstract class BossQuest implements Quest,
Listenable { //Quest(interface) extends Serializable
private transient Status status = Status.IDLE; //This does not work
private String name;
public BossQuest(String name) {
this.name = name;
initialize();
}
//This also does not work
public BossQuest() {
this.status = Status.IDLE;
}
//This was my hacky attempt to forcefully set default values (Does not work)
public void initialize() {
status = Status.IDLE;
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
initialize();
}
public Status getStatus() {
System.out.print("Requesting status!");
if (status == null) {
System.out.print("Status is.. null..?");
}
System.out.print(status);
return status;
}
}
In my code above, Quest extends Serializable
The ONLY time status is null is after I deserialize the file. It CANNOT be set to null through any of the mutators.
Just use readResolve() to initialize the status to IDLE.
Here's a complete example:
public class BossQuest implements Serializable {
private String name;
private transient int status = 42;
public BossQuest(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
private Object readResolve() {
this.status = 42;
return this;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
BossQuest in = new BossQuest("test");
in.setStatus(987);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(in);
oos.close();
byte[] b = baos.toByteArray();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(b));
BossQuest out = (BossQuest) ois.readObject();
System.out.println(out.getName()); // prints test
System.out.println(out.getStatus()); // prints 42
}
}