假设我有一个Serializable类ShapeHolder,它拥有一个实现Serializable Shape接口的对象.我想确保保存正确的具体形状对象(稍后恢复正确的类型).
我怎么能做到这一点?
interface Shape extends Serializable {}
class Circle implements Shape {
private static final long serialVersionUID = -1306760703066967345L;
}
class ShapeHolder implements Serializable {
private static final long serialVersionUID = 1952358793540268673L;
public Shape shape;
}
解决方法:
Java的Serializable会自动为您完成此操作.
public class SerializeInterfaceExample {
interface Shape extends Serializable {}
static class Circle implements Shape {
private static final long serialVersionUID = -1306760703066967345L;
}
static class ShapeHolder implements Serializable {
private static final long serialVersionUID = 1952358793540268673L;
public Shape shape;
}
@Test public void canSerializeShape()
throws FileNotFoundException, IOException, ClassNotFoundException {
ShapeHolder circleHolder = new ShapeHolder();
circleHolder.shape = new Circle();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test"));
out.writeObject(circleHolder);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("test"));
final ShapeHolder restoredCircleHolder = (ShapeHolder) in.readObject();
assertThat(restoredCircleHolder.shape, instanceOf(Circle.class));
in.close();
}
}