如何序列化接口? [英] How can I serialize an interface?

查看:371
本文介绍了如何序列化接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个SerializableShapeHolder,该类拥有一个实现Serializable Shape接口的对象.我想确保保存了正确的混凝土形状对象(以后又恢复了正确的类型).

Suppose I have a Serializable class ShapeHolder that owns an object that implements a Serializable Shape interface. I want to make sure the correct concrete shape object is saved (and the correct type is later restored).

我该怎么做?

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自动为您完成此操作.

Java's Serializable does this for you automatically.

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

这篇关于如何序列化接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆