How can I serialize an interface?

帅比萌擦擦* 提交于 2020-01-10 18:45:34

问题


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).

How can I accomplish this?

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

回答1:


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



回答2:


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



回答3:


I want to make sure the correct concrete shape object is saved (and the correct type is later restored).

Java's default serialization (ObjectInputStream & ObjectOutputStream) does that out-of-the-box. When serializing, Java writes there the name of the concrete class and then uses in when deserializing.



来源:https://stackoverflow.com/questions/10871044/how-can-i-serialize-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!