我正在编写一个程序来将一个对象从一个类发送到另一个类。这是我的程序的一个简短示例,用于表示该问题。如您所见,从服务器发送到客户端的对象是学生类,该类已在每个类(服务器/客户端)中单独定义。我通过发送一个工作正常的 ArrayList 检查了这段代码,但是当涉及到我自己定义的类类型时,我收到了这个错误:
Exception in thread "main" java.lang.ClassCastException: ServerSide$1Student cannot be cast to ClientSide$1Student
at ClientSide.main(ClientSide.java:29)
这是服务器端的代码:
import java.io.*;
import java.net.*;
public class ServerSide {
public static void main(String[] args) {
class Student implements Serializable
{
int id;
public Student(int num){id=num;}
public void setID(int num){id=num;}
public void Print(){System.out.println("id = " + id);}
}
try
{
Student a = new Student(3);
ServerSocket myServerSocket = new ServerSocket(9999);
Socket skt = myServerSocket.accept();
try
{
ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
objectOutput.writeObject(a);
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
而对于客户端是:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSide {
public static void main(String[] args)
{
class Student implements Serializable
{
int id;
public Student(int num){id=num;}
public void setID(int num){id=num;}
public void Print(){System.out.println("id = " + id);}
}
try {
Socket socket = new Socket("10.1.1.2",9999);
try {
ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream());
try {
Object object =(Student) objectInput.readObject();
Student tmp = (Student) object;
tmp.Print();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
编辑:
我将它们移动到同一个文件并添加了序列化 ID。它工作正常。