readobject method throws ClassNotFoundException

送分小仙女□ 提交于 2019-12-17 07:40:21

问题


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.

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

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

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

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

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?


回答1:


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.

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;

    // ...
}



回答2:


The reason is, that the readObject() in ObjectInputStream is practically implemented as:

 String s = readClassName();
 Class c = Class.forName(s); // Here your code breaks
 Object o = c.newInstance();
 ...populate o...


来源:https://stackoverflow.com/questions/2916107/readobject-method-throws-classnotfoundexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!