2014-06-24 123 views
-1

我是JAVA的新手,試圖使用readObject()交換客戶端和服務器之間的對象,但它顯示的是incompatible types : object cannot be converted to ChatData。爲什麼發生錯誤以及如何解決此問題。請告訴我它是如何工作的。不兼容的類型:對象不能轉換爲ChatData

` Socket socket = new Socket("127.0.0.1", 3000); 
    ObjectOutputStream clientWriter; 
    ObjectInputStream clientReader; 
    try { 
     clientWriter = new ObjectOutputStream(socket.getOutputStream()); 
     clientReader = new ObjectInputStream(socket.getInputStream()); 

     ChatData clientOutputData = new ChatData("Hello! This is a message from the client number ", socket.getInetAddress()); 
     clientWriter.writeObject(clientOutputData); 

     ChatData clientInputData = clientReader.readObject(); //Here is the error and the ChatData is another class. 

     try { 
      // do processing 
      Thread.sleep(2000); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); 
     } 

    } catch (IOException ex) { 
     Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); 
    } finally { 
     try { 
      if (clientReader != null) { 
       clientReader.close(); 
      } 
      if (clientWriter != null) { 
       clientWriter.close(); 
      } 
      socket.close(); 
     } catch (IOException ex) { 
      System.err.println("Couldn't close the connection succesfully"); 
      Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
    Thread.sleep(15000); 
    } 
} 
+0

確實將其轉換爲'ChatData'工作? 'ChatData clientInputData =(ChatData)clientReader.readObject();' –

+0

是的,它確實有效。但爲什麼有必要施展它? – DawnEagle999

+0

,因爲java是一種靜態的,強類型的編程語言,所以隱式轉換(你在做什麼)對於編譯器來說是一個很大的問題。 –

回答

2

你應該投的readObject()結果到需要明確類readObject返回類型爲Object

ChatData clientInputData = (ChatData) clientReader.readObject(); 

你也可以把它包裝成try-catch塊,在這樣的情況下,您將能夠處理ClassCastException錯誤:

try { 
    ChatData clientInputData = (ChatData) clientReader.readObject(); 
} catch (ClassCastException e){ 
    //handle error 
} 

還有一個建議:使用IDE這樣的Intellij IDEA或Eclipse,他們會在編譯之前提醒你。

3

readObject()方法返回一個對象類型對象

您必須將接收到的對象轉換爲所需的類型。

ChatData clientInputData = clientReader.readObject(); //Here is the error and the ChatData is another class. 

解決方案:

ChatData clientInputData = (ChatData) clientReader.readObject(); 

您也應該檢查是否接收到的對象是你想要的類型,否則一個ClassCastException可能會被拋出。

Object clientInputData = clientReader.readObject(); 
ChatData convertedChatData = null; 
if(clientInputData instanceof ChatData) { 
    convertedChatData = (ChatData) clientInputData; 
} 
相關問題