I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this?
Here's the part of the code that is causing the err开发者_Python百科or
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();
It seems that your object have to implements both Transferable and Serializable.
Hope this code helps you
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();
with a plop like:
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;
}
}
The vest way around this is to parse each data flavor into a serializable object of it's kind i.e. put string clipboard content into a string object
Your concrete class must implement the Serializable
interface to be able to do so.
* 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.
Hmm. Have you added to your object implements Serializable
?
UPD. Also check that all fields are also serializable. If not - mark them as transient.
精彩评论