我有一个非常简单的类层次结构:为什么我的对象没有正确的反序列化?
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的新实例;序列化它;然后立即反序列化 - 那么反序列化对象既有其字段设置为null的:
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 */
}
当我做基类实现Serializable接口,代码开始正常工作。我的问题是...为什么?
谢谢,爱德华多,这是有道理的(在某种程度上)。这是否意味着基本上没有办法生成一个子类Serializable,而且还没有创建所有的父类Serializable呢?或者,这仍然有可能通过在子类中提供readObject和writeObject的自定义实现? – Bugmaster 2010-12-02 04:17:33