[英]Java: Transferable Objects & Serialization
我需要序列化Transferable對象,我可以通過對象數據流發送它,但在運行時我得到錯誤java.io.NotSerializableException我不知道什么是錯的。 我該如何解決?
這是導致錯誤的代碼部分
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
System.out.println(contents);
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//write objects
oos.writeObject(contents);
oos.close();
您的具體類必須實現Serializable
接口才能執行此操作。
* Thrown when an instance is required to have a Serializable interface.
* The serialization runtime or the class of the instance can throw
* this exception. The argument should be the name of the class.
嗯。 你有沒有添加到你的對象implements Serializable
?
UPD。 還要檢查所有字段是否也可序列化。 如果不是 - 將它們標記為瞬態。
您的對象似乎必須實現Transferable和Serializable。
希望這段代碼可以幫到你
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Initialiaze ObjectStreams
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
clipboard.setContents(new Plop(), null);
final Transferable contents = clipboard.getContents(null);
final Plop transferData = (Plop) contents.getTransferData(new DataFlavor(Plop.class, null));
oos.writeObject(transferData);
oos.close();
像plop一樣:
static class Plop implements Transferable, Serializable{
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return this;
}
}
圍繞這個的背心方法是將每個數據風格解析為它的類型的可序列化對象,即將字符串剪貼板內容放入字符串對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.