readobject方法抛出ClassNotFoundException [英] readobject method throws ClassNotFoundException

查看:146
本文介绍了readobject方法抛出ClassNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java并希望使用Java的客户端/服务器进行测试,以使客户端将自定义类(Message)的简单对象发送到服务器。问题是我一直在服务器端获得一个ClassNotFoundException。

I'm trying to pick up Java and wanted to test around with Java's client/server to make the client send a simple object of a self defined class(Message) over to the server. The problem was that I kept getting a ClassNotFoundException on the server side.

我认为其余的代码似乎没问题,因为String之类的其他对象可以通过问题。

I think the rest of the codes seem to be alright because other objects such as String can go through without problems.

我在客户端和服务器的不同位置有两个不同的netbeans项目。

I had two different netbeans projects in different locations for client and server each.

每个项目在各自的包下拥有自己的Message类副本。
消息类实现Serializable。

Each of them have their own copy of Message class under their respective packages. Message class implements Serializable.

在客户端,我尝试发送一个Message对象。

On the client side, I attempt to send a Message object through.

在服务器端,在调用readObject方法时,它似乎是从客户端的包而不是它自己的包中找到Message类。 printStackTrace显示:服务器端的java.lang.ClassNotFoundException:client.Message

On the server side, upon calling the readObject method, it seems to be finding Message class from the client's package instead of it's own. printStackTrace showed: "java.lang.ClassNotFoundException: client.Message" on the server side

我甚至没有尝试过转换或存储收到的对象。有没有我遗漏的东西?

I have not even tried to cast or store the object received yet. Is there something I left out?

推荐答案

包名和类名必须完全相同双方。即写一次,编译一次然后给双方相同的副本。没有单独的 server.Message client.Message 类,但只有一个共享.Message 类或类似的东西。

The package name and classname must be exactly the same at the both sides. I.e. write once, compile once and then give the both sides the same copy. Don't have separate server.Message and client.Message classes, but a single shared.Message class or something like that.

如果你可以保证相同的包/类名,但并不总是在它的时候相同的副本,然后你需要添加一个 serialVersionUID 字段,该字段与相关的类具有相同的值。

If you can guarantee the same package/class name, but not always whenever it's exactly the same copy, then you need to add a serialVersionUID field with the same value to the class(es) in question.

package shared;

import java.io.Serializable;

public class Message implements Serializable {
    private static final long serialVersionUID = 1L;

    // ...
}

这篇关于readobject方法抛出ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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