Trouble accessing fields of a serialized object in Java

Posted by typoknig on Stack Overflow See other posts from Stack Overflow or by typoknig
Published on 2011-01-16T02:42:10Z Indexed on 2011/01/16 2:53 UTC
Read the original article Hit count: 193

Filed under:
|
|
|

I have instantized a class that implements Serializable and I am trying to stream that object like this:

try{
    Socket socket = new Socket("localhost", 8000);
    ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
    toServer.writeObject(myObject);
} catch (IOException ex) {
    System.err.println(ex);
}

All good so far right? Then I am trying to read the fields of that object like this:

//This is an inner class
class HandleClient implements Runnable{

private ObjectInputStream fromClient;
private Socket socket; // This socket was established earlier

try {
    fromClient = new ObjectInputStream(socket.getInputStream());
    GetField inputObjectFields = fromClient.readFields();

    double myFristVariable = inputObjectFields.get("myFirstVariable", 0);
    int mySecondVariable = inputObjectFields.get("mySecondVariable", 0);

    //do stuff

    } catch (IOException ex) {
        System.err.println(ex);
    } catch (ClassNotFoundException ex) {
        System.err.println(ex);
    } finally {
        try {
            fromClient.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

But I always get the error:

java.io.NotActiveException: not in call to readObject

This is my first time streaming objects instead of primitive data types, what am I doing wrong?

BONUS

When I do get this working correctly, is the ENTIRE CLASS passed with the serialized object (i.e. will I have access to the methods of the object's class)? My reading suggests that the entire class is passed with the object, but I have been unable to use the objects methods thus far. How exactly do I call on the object's methods?

In addition to my code above I also experimented with the readObject method, but I was probably using it wrong too because I couldn't get it to work. Please enlighten me.

© Stack Overflow or respective owner

Related posts about java

Related posts about serialization