我的对象实现了PropertyChangeSupport
,但是当我从 json 字符串反序列化时,变量propertyChangeSupport
将是null
,尽管我new PropertyChangeSupport(this)
在默认构造函数中使用 a 自己初始化了值。如何使用 Gson 正确初始化或反序列化它?
假设我有这个对象:
public class Blah implements BlahInterface {
private PropertyChangeSupport propertyChangeSupport;
protected int id;
protected BlahType type;
public Blah() {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public BlahType getType() {
return type;
}
public void setType(BlahType type) {
this.type = type;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.propertyChangeSupport.addPropertyChangeListener(listener);
}
public PropertyChangeListener[] getPropertyChangeListeners() {
return this.propertyChangeSupport.getPropertyChangeListeners();
}
}
我也试过new PropertyChangeSupport(this);
直接把它放在开头,也不行。我有点想避免手动创建一个函数,例如initializePropertyChangeSupport()
然后在反序列化后手动调用它,因为这有点难看。
我正在尝试做的事情:
JsonArray ja = json.get("blahs").getAsJsonArray();
ja.forEach(item -> {
Blah blah = BlahInterface.Parse(item.toString());
// But here I can't addPropertyChangeListener because propertyChangeSupport is null
// vvvvvvvvvvvv
blah.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
BlahState state = (BlahState) evt.getNewValue();
Logger.debug("Property had been updated, " + state.toString());
}
});
});
这是我的 json 解析函数:
@SuppressWarnings("unchecked")
public static <T extends Blah> T Parse(String json) {
Gson gson = new Gson();
Blah t = new Blah(gson.fromJson(json, Blah.class));
switch (t.getType()) {
case blahone:
return (T) gson.fromJson(json, BlahOne.class);
default:
return (T) t;
}
};