[英]Serialization of an object “that has fields reverenced by a SWT class”
我有点困扰。 我确实了解序列化的概念。 但是,当我尝试对对象进行序列化/反序列化(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不可序列化。 当我只想要DomainObject时,为什么Java会尝试序列化框架?
我认为可能是因为参考了框架。 因此,当我将Serializable-Interface添加到MultiLanguageFrame并将SWT-Components标记为瞬态时,它告诉我找不到有效的构造函数。 我无法添加无参数构造函数,因为从逻辑上讲它毫无意义,而且SWT-Components还需要一个父对象才能存在。
我真的很困扰这个问题,因为我不知道如何解决这个问题。 预先感谢您的答复!
我自己找到了解决方案。 我将其发布,以便其他人可以看到它,这可能会有所帮助。
感谢@ greg-449带领我们前进。 我确实有一个内部类TranslationHelper
,它在MultiLanguageFrame
中扩展了Translation
。 这样做的目的是使我可以为翻译保存一些标志(删除,更改,新),而无需更改Translation
本身。 当我调用frame.getTranslations()
我将元素从TranslationsHelper
为Translation
。 该对象的实例仍然是TranslationHelper
。
现在,所有这些都涉及到了MultiLanguageFrame。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.