Java supports Custom Serialization. Read the section Customize the Default Protocol.
To quote:
There is, however, a strange yet crafty solution. By using a built-in
feature of the serialization mechanism, developers can enhance the
normal process by providing two methods inside their class files.
Those methods are:
- private void writeObject(ObjectOutputStream out) throws
IOException;
- private void readObject(ObjectInputStream in) throws
IOException, ClassNotFoundException;
In this method, what you could do is serialize it into other forms if you need to such as the ArrayList for Location that you illustrated or JSON or other data format/method and reconstruct it back on readObject()
With your example, you add the following code:
private void writeObject(ObjectOutputStream oos)
throws IOException {
// default serialization
oos.defaultWriteObject();
// write the object
List loc = new ArrayList();
loc.add(location.x);
loc.add(location.y);
loc.add(location.z);
loc.add(location.uid);
oos.writeObject(loc);
}
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
// default deserialization
ois.defaultReadObject();
List loc = (List)ois.readObject(); // Replace with real deserialization
location = new Location(loc.get(0), loc.get(1), loc.get(2), loc.get(3));
// ... more code
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…