我有点被一个问题困住了。我确实理解序列化的概念。然而,当我尝试序列化/反序列化(deepCopy)对象时,我会出错:
我有一个包含信息的基本域对象(两个文件):
public class DomainObject implements java.io.Serializable {
private String defaultDescription = "";
private List<Translation> translations;
public DomainObject() {
;
}
public void setTranslations(final List<Translation> newTranslations) {
this.translations = newTranslations;
}
public List<Translation> getTranslations() {
return this.translations;
}
public void setDefaultDescription(final String newDescription) {
this.defaultDescription = newDescription;
}
public String getDefaultDescription() {
return this.defaultDescription;
}
}
public class Translations implements java.io.Serializable {
private String description = "";
public Translation() {
;
}
public void setDescription(final String newDescription) {
this.description = newDescription;
}
public String getDescription() {
return this.description;
}
}
我还有一个框架,用户可以填写这个域对象的所有必要信息。由于我有多个域对象(本例仅显示一个)具有不同的字段,因此每个域对象具有不同的帧。这些框架中的每一个都包括一个“多语言框架”(MultiLanguageFrame),该框架使用户能够为该域对象的描述添加可选翻译。
public class MultiLanguageFrame extends org.eclipse.swt.widgets.Composite {
private List<Translation> translations = new ArrayList<Translation>();
public MultiLanguageFrame(final Composite parent, final int style) {
super(parent, style);
...
}
public List<Translation> getTranslations() {
return translations;
}
}
我通过此方法深度复制对象:
...
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception t) {
logger.error(deepCopy() error: " + t.getMessage()); //$NON-NLS-1$
throw new RuntimeException("deepCopy() error", t); //$NON-NLS-1$
}
现在来看错误:
当我尝试这样做时:
MultiLanguageFrame frame = new MultiLanguageFrame(parent, SWT.NONE);
DomainObject dom = new DomainObject();
dom.setDefaultDescription("Testobject");
dom.setTranslations(frame.getTranslations())
deepCopy(dom);
我收到一个错误,告诉我MultiLanguageFrame不可序列化。当我只想要那个域对象时,为什么Java会尝试序列化这个框架?
我想可能是因为框架中的参照。因此,当我将可序列化接口添加到MultiLanguageFrame并将SWT组件标记为
转瞬即逝的
它告诉我没有找到有效的构造函数。我不能添加无参数构造函数,因为它在逻辑上没有意义,而且SWT组件也需要父级才能存在。
我真的被这个问题困住了,因为我不知道如何解决这个问题。感谢您提前回答!