[英]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.