您应该首先问问自己是否真的想在这里使用对象序列化。最好使用不同的持久性方法:例如,使用JSON封送库,例如
GSON
。大多数这样的库只使用对象的
get
和
set
EventsBean
使用很少的额外代码初始化。
事件bean
班
Serializable
。通常这很简单,但您将遇到的问题是JavaFX属性类没有实现
真是太天真了
使生效
尝试序列化它的实例将生成运行时异常。要做到这一点,需要使用自定义序列化。
首先,创建JavaFX属性
transient
readObject
和
writeObject
定义对象应如何序列化的方法:
public class EventsBean implements Serializable {
private transient SimpleStringProperty event;
private transient SimpleObjectProperty<LocalDate> date;
private transient SimpleStringProperty done;
private transient SimpleStringProperty observation;
private transient SimpleBooleanProperty selected;
// constructors...
// example get/set/property methods:
public StringProperty eventProperty() {
return event ;
}
public final String getEvent() {
return eventProperty().get();
}
public final void setEvent(String event) {
eventProperty().set(event);
}
// etc. for other properties...
// custom serialization:
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(getEvent()); // write event as a plain String
s.writeObject(getDate());
s.writeObject(getDone());
s.writeObject(getObservation());
s.writeBoolean(isSelected());
}
// custom deserialization:
private void readObject(ObjectInputStream s) throws IOException {
s.defaultReadObject();
this.event = new SimpleStringProperty((String)s.readObject());
this.data = new SimpleObjectProperty<>((LocalDate)s.readObject());
this.done = new SimpleStringProperty((String)s.readObject());
this.observation = new SimpleStringProperty((String)s.readObject());
this.selected = new SimpleBooleanProperty(s.readBoolean());
}
}
ObservableList
实现通常不可序列化,因此需要序列化“常规”列表以序列化数据,即:
ObjectOutputStream s = ... ;
s.writeObject(new ArrayList<EventsBean>(dataList));
回过头来看:
ObjectInputStream s = ... ;
dataList.setAll((List<EventsBean>)s.readObject());