2014-06-24 53 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; 
} 
相关问题