ObjectInputStream readObject(): ClassNotFoundException

倾然丶 夕夏残阳落幕 提交于 2019-12-04 04:31:55

问题


In both client and server classes, I have an exact same inner class called Data. This Data object is being sent from the server using:

ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream());
output.writeObject(d);

(where d is a Data object)

This object is received on the client side and cast to a Data object:

ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
Object receiveObject = input.readObject();
if (receiveObject instanceof Data){
    Data receiveData = (Data) receiveObject;
    // some code here... 
}

I'm getting a java.lang.ClassNotFoundException: TCPServer$Data on this line Object receiveObject = input.readObject();

My guess is that it's trying to to look for the Data class in the Server side and can't find it, but I'm not sure... How do I fix this?


回答1:


What you were trying to do is something along the lines of the following:

class TCPServer {
    /* some code */

    class Data {

    }
}

class TCPClient {
    /* some code */

    class Data {

    }
}

Then you are serializing a TCPServer$Data and trying to unserialize it as a TCPClient$Data. Instead you are going to want to be doing this:

class TCPServer {
    /* some code */

}

class TCPClient {
    /* some code */

}

class Data {
    /* some code */

}

Then make sure the Data class is available to both the client and the server programs.




回答2:


When you use some class in two different JVMs, and you are marshalling/unmarshalling the class then the class should be exported to a common library and shared between both server and client. Having different class wont work any time.

What you are trying to do is marshall TCPServer$Data and unmarshall as TCPClient$Data. That is incompatible.



来源:https://stackoverflow.com/questions/11745771/objectinputstream-readobject-classnotfoundexception

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