readobject method throws ClassNotFoundException

后端 未结 2 1298
谎友^
谎友^ 2020-11-30 12:57

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.

相关标签:
2条回答
  • 2020-11-30 13:34

    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...
    
    0 讨论(0)
  • 2020-11-30 13:46

    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;
    
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题