如何序列化界面?

时间:2012-06-03 14:12:24

标签: java oop serialization types

假设我有一个SerializableShapeHolder,它拥有一个实现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;
}

3 个答案:

答案 0 :(得分:7)

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();
   }
}

答案 1 :(得分:0)

import java.io.*;

public class ExampleSerializableClass implements Serializable {
    private static final long serialVersionUID = 0L;

    transient private Shape shape;
    private String shapeClassName;

    private void writeObject(ObjectOutputStream out) throws IOException {
        shapeClassName = shape.getClass().getCanonicalName();
        out.defaultWriteObject();
    }

    private void readObject(ObjectInputStream in) 
           throws IOException, ClassNotFoundException, 
              InstantiationException, IllegalAccessException {
        in.defaultReadObject();
        Class<?> cls = Class.forName(shapeClassName);
        shape = (Shape) cls.newInstance();
    }
}

答案 2 :(得分:0)

  

我想确保保存正确的具体形状对象(稍后恢复正确的类型)。

Java的默认序列化(ObjectInputStream&amp; ObjectOutputStream)可以实现开箱即用。在序列化时,Java会在那里写入具体类的名称,然后在反序列化时使用。