Lets imagine I have the following Java class:
public class ImaginaryClass implements Serializable {
private List<SomeData> someData;
private transient boolean isSynced;
public ImaginaryClass() {
this.load();
}
public void addSomeData(SomeData data) {
this.someData.add(data);
this.isSynced = false;
this.save();
}
private void load() {
// Deserialize "this" instance of the object
this.isSynced = true;
}
private void save() {
// Serialize "this" instance of the object
this.isSynced = true;
}
}
My goal is to encapsulate the serialization and deserialization of an objects instance within the objects own class. I have many classes to implement that require special "treatment" and therefore this is the easiest design I've come up with so far.
But, I'm running into problems, I can't reassign the reference this
so I'm under the impression this is not going to work. In Java is my above example possible? How do I make this work?
You can't reassign this
, what you do in a Serializable object is to serialize / de-serialize all non transient non static fields.
Your idea of creating a new instance of the object is not bad.
If you create a brand new object you should return it as a new reference, in this case you can either have a factory which builds the object by loading it from some persistent storage, like:
ImaginaryClass objImg = ImaginaryClassFactory.newInstace().loadImaginaryClass();
Or you can do that in a public static
method in the class itself:
public class ImaginaryClass implements Serializable {
public static ImaginaryClass load(){
....
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.