How can I serialize an interface?

后端 未结 3 1636
后悔当初
后悔当初 2021-01-02 03:53

Suppose I have a Serializable class ShapeHolder that owns an object that implements a Serializable Shape interface. I wa

3条回答
  •  梦毁少年i
    2021-01-02 04:26

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

提交回复
热议问题