Java:Transferable Objects&序列化

时间:2011-09-21 12:45:19

标签: java serialization stream data-transfer-objects

我需要序列化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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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。 还要检查所有字段是否也可序列化。如果不是 - 将它们标记为瞬态。

答案 2 :(得分:1)

您的对象似乎必须实现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;
    }
}

答案 3 :(得分:1)

围绕这个的背心方法是将每个数据风格解析为它的可序列化对象,即将字符串剪贴板内容放入字符串对象