java - 如何序列化接口(interface)?

标签 java oop serialization types

假设我有一个 SerializableShapeHolder,它拥有一个实现 Serializable Shape 接口(interface)的对象。我想确保保存了正确的具体形状对象(并且稍后恢复了正确的类型)。

我怎样才能做到这一点?

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

关于java - 如何序列化接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871044/

相关文章:

java - 数据在 for 循环中的数组列表内的数组列表中重复 Recylerview Koltin

java - 将 HTML/CSS 设计的网站模板迁移到 google web 工具包?

javascript - 重构Javascript继承结构

c++ - 使用头文件制作ADT : declaration of ‘int Queue::size()’ outside of class is not definition [-fpermissive]

vb.net - 在 VB.Net 中序列化 ObservableCollection(of T)

java - 如何将单个 GSON 自定义序列化器应用于所有子类?

Ruby 对象到 JSON 并返回

Java和C#通过消息队列进行通信

java - 在 R 3.6 上为 ubuntu 仿生海狸安装 rJava 时出现 "Unable to run a simple JNI program"错误消息

c++ - 客户端服务器编程 - 写入缓冲区