gpt4 book ai didi

java - 为什么我的对象没有正确反序列化?

转载 作者:行者123 更新时间:2023-12-03 23:23:16 25 4
gpt4 key购买 nike

我有一个非常简单的类层次结构:

public class DropdownOption<T> /* does NOT implement Serializable */ {
private T value;
private String label;

public DropdownOption() {
this (null, null);
}

public DropdownOption(T value, String label) {
this.value = value;
this.label = label;
}

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}

public String getLabel() {
return label;
}

public void setLabel(String label) {
this.label = label;
}
}

/**
* Convenience decorator
*/
public class LongIdDropdownOption extends DropdownOption<Long>
implements Serializable {

private static final long serialVersionUID = -3920989081132516015L;

public LongIdDropdownOption() {
super();
}

public LongIdDropdownOption(Long value, String label) {
super(value, label);
}

public Long getId() {
return getValue();
}

public void setId(Long id) {
super.setValue(id);
}
}

当我创建 LongIdDropdownOption 的新实例时,它确实实现了 Serializable;序列化它;然后立即反序列化它——然后反序列化对象的两个字段都设置为空:

public void testSerialization() throws Exception {
LongIdDropdownOption option = new LongIdDropdownOption(1L, "One");

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(buffer);
os.writeObject(option);
os.close();

ObjectInputStream is = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
LongIdDropdownOption result = (LongIdDropdownOption) is.readObject();
is.close();

assertNotNull(result);
assertEquals("One", result.getLabel()); /** Fails, label is null */
}

当我使基类实现可序列化时,代码开始正常工作。我的问题是……为什么?

最佳答案

如此处所述 - http://java.sun.com/developer/technicalArticles/ALT/serialization “覆盖 readObject 和 writeObject 的一个常见原因是为本身不可序列化的父类(super class)序列化数据”。​​

您认为您在子类实例中拥有的状态对于序列化来说并不真正可见,因为它没有通过您的 API 或反射。就序列化过程而言,状态属于未实现 Serializable 的父类(super class)。这就是您失去它的地方。

这里有一个 Java 对象序列化规范的链接,应该对此进行解释: http://download.oracle.com/javase/6/docs/platform/serialization/spec/serialTOC.html

关于java - 为什么我的对象没有正确反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4331564/

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