使用自定义可序列化表单并序列化您需要的数据。例如。
import javafx.scene.canvas.GraphicsContext ;
import javafx.scene.paint.Color ;
import javafx.geometry.Rectangle2D;
import java.io.Serializable ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;
import java.io.IOException ;
public class DrawableRect implements Drawable, Serializable {
private transient Color color ;
private transient Rectangle2D bounds ;
public DrawableRect(Color color, Rectangle2D bounds) {
this.color = color ;
this.bounds = bounds ;
}
@Override
public void draw(GraphicsContext g) {
g.setFill(color);
g.fillRect(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight());
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// write color:
s.writeDouble(color.getRed());
s.writeDouble(color.getGreen());
s.writeDouble(color.getBlue());
s.writeDouble(color.getOpacity());
// write bounds:
s.writeDouble(bounds.getMinX());
s.writeDouble(bounds.getMinY());
s.writeDouble(bounds.getWidth());
s.writeDouble(bounds.getHeight());
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
double r = s.readDouble();
double g = s.readDouble();
double b = s.readDouble();
double opacity = s.readDouble();
color = new Color(r,g,b,opacity);
double x = s.readDouble();
double y = s.readDouble();
double w = s.readDouble();
double h = s.readDouble();
bounds = new Rectangle2D(x,y,w,h);
}
}
如果您有可序列化的字段(或原始类型),则无需标记它们transient
,以及defaultReadObject
and defaultWriteObject
会处理他们的。如果您有不可序列化的字段,请标记它们transient
并将数据序列化为可序列化的形式,如示例所示。
显然,由于您有此接口的多个实现,这些实现可能都需要此功能,因此使用一些静态方法创建一个辅助类可能会对您有利:
public class DrawableIO {
public static void writeColor(Color color, ObjectOutputStream s) throws IOException {
s.writeDouble(color.getRed());
s.writeDouble(color.getGreen());
s.writeDouble(color.getBlue());
s.writeDouble(color.getOpacity());
}
public static Color readColor(ObectInputStream s) throws IOException {
double r = s.readDouble();
double g = s.readDouble();
double b = s.readDouble();
double opacity = s.readDouble();
return new Color(r,g,b,opacity);
}
public static void writeBounds(Rectangle2D bounds, ObjectOutputStream s) throws IOException {
s.writeDouble(bounds.getMinX());
s.writeDouble(bounds.getMinY());
s.writeDouble(bounds.getWidth());
s.writeDouble(bounds.getHeight());
}
public static Rectangle2D readBounds(ObjectInputStream s) throws IOException {
double x = s.readDouble();
double y = s.readDouble();
double w = s.readDouble();
double h = s.readDouble();
return new Rectangle2D(x,y,w,h);
}
}
然后当然是你的方法Drawable
实现减少到类似
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
DrawableIO.writeColor(color, s);
DrawableIO.writeBounds(bounds, s);
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
color = DrawableIO.readColor(s);
bounds = DrawableIO.readBounds(s);
}