简体   繁体   中英

Exception when casting object to string on different machine

When trying to cast from an Object, (which should be a serialised string) to a String, on one machine it works fine, but on another it brings up an exception.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.String

Both machines run the same versions of Ubuntu (14.04 LTS) and the same version of Java (1.7.0_51). Code is as follows,

ois = new ObjectInputStream(connectionSocket.getInputStream());
while(true)
    {
        data = (String) ois.readObject(); //Error Here
        System.out.println(data);
    }

The object input stream works successfully over sockets, and the whole program runs well on other machines (even with different version of linux and Java). Watching for TCP traffic indicates that the string is being sent correctly. What could cause this to happen, and is there any way to make this work universally?

Thank you.

While I have no idea why the same code would perform differently on two supposedly similarly configured machines, I'd propose changing your code to read to an object and then only cast it to a string if you know it is one. If it isn't...and you aren't expecting that, then you can log it, throw an exception or do something else that is of use.

So maybe something like;

while(true)
{
    object obj = ois.readObject(); 
    if (obj instanceof String)
    {
        data = (String) obj;
        System.out.println(data);
    }
    else 
    {
        // Do whatever makes sense here for you
        // If you are testing, then maybe dump whatever info you
        // can to a log file to help you understand what you are reading
        // from the socket and how you could handle that gracefully in 
        // a production environment.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM