The readobject method throws a ClassNotFoundException

I am trying to pick up Java and want to test with the Java client / server so that the client sends a simple object of a self-defined class (Message) to the server. The problem was that I kept getting a ServerName ClassNotFoundException.

I think the rest of the codes look fine, because other objects like String can pass without problems.

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

Each of them has its own copy of the Message class under their respective packages. The message class implements Serializable.

On the client side, I am trying to send a Message object via.

On the server side, by calling the readObject method, it seems like looking for the Message class from the client package instead of its own. printStackTrace showed: "java.lang.ClassNotFoundException: client.Message" on the server side

I did not even try to display or save the resulting object. Is there something I forgot?

+7
java classnotfoundexception client
source share
2 answers

The package name and class name must be exactly the same on both sides. That is, write once, compile once, and then give both sides the same copy. They do not have separate classes server.Message and client.Message , but one class shared.Message or something like that.

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

 package shared; import java.io.Serializable; public class Message implements Serializable { private static final long serialVersionUID = 1L; // ... } 
+16
source share

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

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

All Articles