Search code examples
javaserializationclassnotfoundexception

Why not putting the definition of classes serialization in a shared package results in a `ClassNotFoundException`?


I have a client and server which use serialization to send an array of Shape from server to client. I have written all code and there is no error in them as far as a create a shared package between client program and the server program. However when I create two separate projects and for each if the projects I create Shape.java with the same content as the other one has but this time as I connect client to server it gives me a ClassNotFoundException. Why on the earth it doesn't give error when I put Shape.java in a shared package but as soon as I create a copy and paste that to Server's program, it gives me ClassNotFoundException? I really need that because I want to send my code to my friend and he has a seperate project using this serialized object.


Solution

  • why should I create [the class] in the same package?

    Because Shape is not the name of the class, only a part of it. Java identifies classes by their full name, which includes package.

    If you define Shape on the server as com.myserver.Shape and on the client as com.myclient.Shape, JVM would correctly treat the two classes as unrelated.

    A common approach is to make a special package for your data exchange objects, e.g. com.shared.dto.Shape, and use it on both sides of communication.

    If you need to share your project with someone else, make a separate jar with your DTOs, and another jar with the client library. Build the client code using the client library and the DTO jar. This will ensure that the client would be able to communicate with the server built against the same DTO jar.