本文介绍了ObjectInputStream readObject():ClassNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在客户端和服务器类中,我都有一个名为Data的完全相同的内部类。使用以下命令从服务器发送此Data对象:

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);

(其中d是数据对象)

在客户端收到此对象并转换为Data对象:

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...
}

我得到了a $ code> java.lang.ClassNotFoundException:此行上的TCPServer $ Data Object receiveObject = input.readObject();

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

我的猜测是它试图在服务器端寻找Data类而无法找到它,但我不确定...我该如何修复这个?

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?

推荐答案

你要做的是以下几点:

class TCPServer {
    /* some code */

    class Data {

    }
}

class TCPClient {
    /* some code */

    class Data {

    }
}

然后,您正在序列化TCPServer $ Data并尝试将其反序列化为TCPClient $ 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.

这篇关于ObjectInputStream readObject():ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:53