我的对象实现了PropertyChangeSupport,但是当我从json字符串反序列化时,变量propertyChangeSupport将是null,尽管我自己在默认构造函数中使用new PropertyChangeSupport(this)初始化了该值。如何使用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;
}
};发布于 2017-09-25 14:19:51
这个问题的解决方案是在我的对象中实现InstanceCreator<T>。这样,当Gson试图反序列化对象时,它将调用createInstance函数,该函数依次返回一个带有初始化PropertyChangeSupport变量的适当对象。下面是示例代码:
public class Blah implements InstanceCreator<Blah> {
private final transient PropertyChangeSupport pcs = new PropertyChangeSupport(this);
...
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
@Override
public Blah createInstance(Type type) {
return new Blah();
}
}注意:pcs上存在瞬态关键字,这样Gson就可以在序列化期间跳过它,否则Gson会抛出异常。
https://stackoverflow.com/questions/46371125
复制相似问题