gpt4 book ai didi

具有不可序列化部分的 Java 序列化

转载 作者:IT老高 更新时间:2023-10-28 20:28:39 25 4
gpt4 key购买 nike

我有:

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

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

更正:MyClass2 当然不是接口(interface)而是类。

最佳答案

正如其他人所说,Josh Bloch 的 Effective Java 的第 11 章是Java序列化中不可缺少的资源。

该章节中与您的问题相关的几点:

  • 假设您想要序列化 ​​MyClass2 中不可序列化字段的状态,MyClass 必须可以直接或通过 getter 和 setter 访问该字段。 MyClass 必须通过提供 readObject 和 writeObject 方法来实现自定义序列化。
  • 不可序列化字段的 Class 必须有一个 API 以允许获取其状态(用于写入对象流),然后使用该状态实例化一个新实例(稍后从对象流中读取时)。
  • 根据 Effective Java 的第 74 条,MyClass2 必须有一个 MyClass 可访问的无参数构造函数,否则 MyClass 不可能扩展 MyClass2 并实现 Serializable。

我在下面写了一个简单的例子来说明这一点。


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

关于具有不可序列化部分的 Java 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/95181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com