[英]java.lang.ClassCastException when receiving object with readObject()
我在客戶端有一個bean類,用於存儲用戶輸入數據並通過套接字將其發送到服務器。 服務器具有相同的Bean類。
服務器接收對象,但是當我嘗試將接收到的內容分配給Bean類的實例時,會導致以下錯誤:
java.lang.ClassCastException: ie.gmit.sw.client.methods.Client cannot be cast to ie.gmit.sw.server.methods.Client
出現錯誤的類:
public class DriveableImpl implements Driveable{
private Client client;
private ObjectOutputStream out;
private ObjectInputStream in;
public DriveableImpl() {
client = new Client();
}
// Method that receives connection socket and open in/out streams for current session
@Override
public void connect(Socket socket){
try {
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean login() throws Exception {
// Program crash here
client = (Client) in.readObject();
System.out.println(client.toString());
return false;
}
}
我使用InvocationHandler來調用上述類中實現的方法:
public class MethodInvoker implements InvocationHandler{
private Object returnObject = null; // object that will hold any returns from invoked methods
private final Driveable userInterface;
protected MethodInvoker(Driveable ui) {
this.userInterface = ui;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException{
System.out.println("BEFORE");
returnObject = method.invoke(userInterface, args);
System.out.println(method.getName());
System.out.println("AFTER");
return returnObject; // could problem be possibly here?
}
}
我真的不確定這里發生了什么,因為它可以在客戶端-服務器應用程序的簡單設計中工作。 我認為我正在發布與錯誤相關的程序部分,但是如果發生任何請求,我將修改帖子。
謝謝!
注意序列化錯誤:
它明確指出您有2個不同的類(也許它們看起來完全一樣),但是它們位於不同的包中:
ie.gmit.sw.**client**.methods
ie.gmit.sw.**server**.methods
這意味着,從Java的角度來看,它們是完全無關的
ie.gmit.sw.client.methods.Client cannot be cast to ie.gmit.sw.server.methods.Client
這就是為什么您有一個類強制轉換異常的原因
在Java中,Same Class表示它駐留在相同的程序包中並且具有相同的名稱。 因此,服務器和客戶端應具有相同的類。 有兩種方法可以實現此目的:
只需將相同的類放置兩次-一次在客戶端,一次在服務器。 對您而言,這意味着-將包重命名為通用名稱。 由於代碼重復,這是一種不好的方法
將將序列化的對象放入第三個“ common”模塊(將從中生成jar),然后在運行客戶端和服務器時使它們依賴於此模塊。 因此,從物理上講,您只有一個“客戶端”類的副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.