使用 RMI 进行 Java 序列化 [英] Java Serialization with RMI

查看:34
本文介绍了使用 RMI 进行 Java 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 Java RMI 的项目.这是导致问题的类:

I'm working on a project using Java RMI. This is the class causing problem:

public class FSFile implements Serializable 
{
public static final int READ    = 0;
public static final int WRITE   = 1;

private int     flag;
private String  filename;

private transient BufferedWriter  writer;
private transient BufferedReader  reader;

...

private void writeObject(ObjectOutputStream stream) throws IOException
{
    stream.defaultWriteObject();
    stream.writeObject(writer);
    stream.writeObject(reader);    
}

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
{
    stream.defaultReadObject();
    writer      = (BufferedWriter) stream.readObject();
    reader      = (BufferedReader) stream.readObject();
}
}

基本上,我使用 RMI 将该 FSFile 对象发送到本地的另一个进程(目前),这是我得到的错误:

Basically, I use RMI to send that FSFile object to another process locally (for now) and here's the error I get:

java.rmi.UnmarshalException: error unmarshalling return; nested exception is:                                                                      
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException;
java.io.BufferedReader

更准确地说,有一个名为 FileService 的类,它使用来自 FileServer 的函数 fetch() 来获取 FSFile 作为回报.fetch() 函数没有什么特别之处,它只是创建一个 FSFile 并返回它.这些类之间的所有通信都是通过 RMI 进行的.

To be more precise, there's one class named FileService which use a function fetch() from a FileServer to get a FSFile in return. There is nothing special in the fetch() function, it just creates a FSFile and returns it. All communications between those classes are made via RMI.

我怎么会有这样的错误?

How come I have an error like this ?

推荐答案

你不能序列化读者和作者.这个不成立.这就像尝试通过电话线发送电话一样.如果要发送文件,请发送文件.

You can't serialize readers and writers. It makes no sense. It's like trying to send a telephone over a telephone line. If you want to send a file, send the file.

您的代码只是在这些对象上调用 writeObject,就好像它们是可序列化的一样.他们不是.否则,您可以使它们成为非瞬态并完全省略自定义 readObject 和 writeObject 方法.只是重新编码系统无论如何都会做的事情不会改变任何东西.它当然不会使类 Serializable 不是.

And your code just calls writeObject on these objects as though they were Serializable. They aren't. Otherwise you could have made them non-transient and omitted the custom readObject and writeObject methods altogether. Just re-coding what the system would have done anyway doesn't change anything. It certainly doesn't make classes Serializable that aren't.

这篇关于使用 RMI 进行 Java 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆