1

我需要序列化一个 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();
4

4 回答 4

2

看来您的对象必须同时实现 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();

扑通一声:

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;
    }
}
于 2011-09-21T13:51:59.750 回答
2

解决这个问题的最佳方法是将每个数据风格解析为它的可序列化对象,即将字符串剪贴板内容放入字符串对象

于 2011-10-20T11:04:09.250 回答
1

您的具体类必须实现Serializable接口才能这样做。

于 2011-09-21T12:48:40.160 回答
1
 * 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。还要检查所有字段是否也是可序列化的。如果不是 - 将它们标记为瞬态。

于 2011-09-21T12:48:57.343 回答