代码之家  ›  专栏  ›  技术社区  ›  Burkhard

使用非序列化部件进行Java序列化

  •  52
  • Burkhard  · 技术社区  · 16 年前

    我有:

    class MyClass extends MyClass2 implements Serializable {
      //...
    }
    

    在MyClass2中是不可序列化的属性。如何序列化(和反序列化)此对象?

    更正:当然,myClass2不是接口,而是类。

    10 回复  |  直到 16 年前
        1
  •  49
  •   Scott Bale    16 年前

    Effective Java

    
    class MyClass extends MyClass2 implements Serializable{
    
      public MyClass(int quantity) {
        setNonSerializableProperty(new NonSerializableClass(quantity));
      }
    
      private void writeObject(java.io.ObjectOutputStream out)
      throws IOException{
        // note, here we don't need out.defaultWriteObject(); because
        // MyClass has no other state to serialize
        out.writeInt(super.getNonSerializableProperty().getQuantity());
      }
    
      private void readObject(java.io.ObjectInputStream in)
      throws IOException {
        // note, here we don't need in.defaultReadObject();
        // because MyClass has no other state to deserialize
        super.setNonSerializableProperty(new NonSerializableClass(in.readInt()));
      }
    }
    
    /* this class must have no-arg constructor accessible to MyClass */
    class MyClass2 {
    
      /* this property must be gettable/settable by MyClass.  It cannot be final, therefore. */
      private NonSerializableClass nonSerializableProperty;
    
      public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) {
        this.nonSerializableProperty = nonSerializableProperty;
      }
    
      public NonSerializableClass getNonSerializableProperty() {
        return nonSerializableProperty;
      }
    }
    
    class NonSerializableClass{
    
      private final int quantity;
    
      public NonSerializableClass(int quantity){
        this.quantity = quantity;
      }
    
      public int getQuantity() {
        return quantity;
      }
    }
    
        2
  •  35
  •   Mike Deck    16 年前

    private transient Foo foo;
    

        3
  •  15
  •   MSX    8 年前

    private transient SomeClass myClz;
    

    Kryo object->bytes->object

    Kryo kryo = new Kryo();
    // #### Store to disk...
    Output output = new Output(new FileOutputStream("file.bin"));
    SomeClass someObject = ...
    kryo.writeObject(output, someObject);
    output.close();
    // ### Restore from disk...
    Input input = new Input(new FileInputStream("file.bin"));
    SomeClass someObject = kryo.readObject(input, SomeClass.class);
    input.close();
    

    kryo.register(SomeObject.class, new DeflateCompressor(new FieldSerializer(kryo, SomeObject.class)));
    
        4
  •  11
  •   ykaganovich Mike Samuel    12 年前

        5
  •  6
  •   jediz 114326671    7 年前

    writeObject() readObject() java.io.Serializable

        6
  •  5
  •   Steve Jessop    16 年前

        7
  •  4
  •   Hank    16 年前

        9
  •  3
  •   Boris Terzic    9 年前
        10
  •  2
  •   Tom Hawtin - tackline    16 年前