I have a program with a class similar to the basic example below:
public class Vertex extends Circle implements Serializable {
private int vertexID;
private final static double SIZE = 10.0;
// Constructor
public Vertex(int ID, double x, double y) {
super(x, y, SIZE, Color.BLUE);
this.vertexID = ID;
}
}
What I'd like to be able to do is write a List<Vertex> myVertices
to a file using the ObjectOutputStream
, which requires that each class implements the Serializable
interface. An example is shown below:
FileChooser fc = new FileChooser();
File fileChosen = fc.showOpenDialog(window);
try {
FileOutputStream fOutStream = new FileOutputStream(fileChosen);
ObjectOutputStream oOutStream = new ObjectOutputStream(fOutStream);
oOutStream.writeObject(myVertices);
oOutStream.close();
} catch {
// Exception handling here
}
The problem with the implementation above is that, although Vertex
implements Serializable
, the super class Circle
and its super class Shape
do not implement Serializable
. The result is that the file contains the Vertex
objects but all Shape
details are lost and default to 0.
Is there a simple solution to this sort of problem? My only current option seems to be to create my own Shape
/ Circle
that stores the location/display data as doubles so that it can then be Serializable
. Obviously for one class this isn't too much effort, but I have a few other Shape
objects I'd like to save as well. I would, I assume, then have to either construct actual Shape
objects to display them.
Thanks!
You need to create a writeObject/readObject method which saves the additional state that you need.
Serialization - readObject writeObject overrides
Uses of readObject/writeObject in Serialization
Why are readObject and writeObject private, and why would I write transient variables explicitly?
In case somebody wants to see the actual code for a Shape
, specifically Circle
object, here is what I implemented thanks to the accepted answer. Also included an example of a List<Vertex> myVertices = new ArrayList()
:
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeInt(vertexID);
oos.writeObject(myVertices);
oos.writeDouble(super.getCenterX());
oos.writeDouble(super.getCenterY());
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Read in same order as write
this.vertexID = ois.readInt();
this.myVertices = (List<Vertex>) ois.readObject();
super.setCenterX(ois.readDouble());
super.setCenterY(ois.readDouble());
// Default Circle properties
super.setRadius(SIZE); // Default
super.setFill(Color.BLUE); // Default
}
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.