简体   繁体   English

Java:可转换对象和序列化

[英]Java: Transferable Objects & Serialization

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. 我需要序列化Transferable对象,我可以通过对象数据流发送它,但在运行时我得到错误java.io.NotSerializableException我不知道什么是错的。 How do I fix this? 我该如何解决?

Here's the part of the code that is causing the error 这是导致错误的代码部分

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.

Hmm. 嗯。 Have you added to your object implements Serializable ? 你有没有添加到你的对象implements Serializable

UPD. UPD。 Also check that all fields are also serializable. 还要检查所有字段是否也可序列化。 If not - mark them as transient. 如果不是 - 将它们标记为瞬态。

It seems that your object have to implements both Transferable and Serializable. 您的对象似乎必须实现Transferable和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: 像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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM