私は非常に単純なクラス階層を持っています:
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);
}
}
Serializableを実装する LongIdDropdownOption の新しいインスタンスを作成すると、それをシリアル化します。次に、すぐに逆シリアル化します。逆シリアル化されたオブジェクトの両方のフィールドが 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 を実装すると、コードが正しく機能し始めます。私の質問は...なぜですか?