Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize an interface?

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;
}
like image 912
Jeff Axelrod Avatar asked Jun 03 '12 14:06

Jeff Axelrod


1 Answers

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();
   }
}
like image 200
Jeff Axelrod Avatar answered Oct 16 '22 10:10

Jeff Axelrod