不兼容的类型:对象无法转换为ChatData

时间:2014-06-24 10:33:30

标签: java sockets

我是JAVA的新手,并尝试使用readObject()在客户端和服务器之间交换对象,但它显示incompatible types : object cannot be converted to 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);
    }
 } 

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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,他们会在编译前警告你。