How can I serialize an interface?

21,831

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();
   }
}
Share:
21,831
Jeff Axelrod
Author by

Jeff Axelrod

I'm an independent Android developer currently working on an educational application. It's important to me to continuously improve development techniques so I can maximize the "ilities" of software I write (reliability, maintainability, testability, understandability, etc.) Here's a mind map of tools and technologies I am presently using or investigating. You can click on hyperinks to bring you to related sites. I'm particularly interested in using Model-Driven Software Development to keep my architecture consistent and well documented. I am not yet using Scala on Android for anything other than testing, but plan to eventually migrate to Scala for the application code. Some of my favorite books: Effective Java (Bloch) Programming in Scala (Ordesky) Refactoring - Improving the Design of Existing Code (Fowler et al) Some favorite tools: Eclipse Guice + RoboGuice for dependency injection, though plan to replace this soon as startup is much too slow on Android OrmLite (ORM that works well on Android) Robotium for Android integration testing Eclispe EMF for MDSD Powermock + Mockito for mocking I learned a lot from Software Engineering Radio in its heyday.

Updated on June 05, 2020

Comments

  • Jeff Axelrod
    Jeff Axelrod almost 4 years

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