Chris Headleand
Chris Headleand

Reputation: 6193

Reconstructing serialized objects

Im trying to reconstruct a serialized object and access data from it.

This is how Im sending the object.

    Socket socket = new Socket ("localhost", port);
    ObjectOutputStream out = new ObjectOutputStream (socket.getOutputStream());
    Tester t = new Tester("test");
    out.writeObject(t);
    out.flush();

And this is how I'm receiving it

// This is how the server is being built

    private ServerSocket server;
    server = new ServerSocket(port);
    newsocket = server.accept();

// And this is how Im actually getting the object

    ObjectInputStream input = new ObjectInputStream(newSocket.getInputStream());
    Tester obj = (Tester) input.readObject();
    System.out.println(obj.getText());

However I only get the following output

[Ljava.lang.StackTraceElement;@237360be 

What I was hoping to get was the string I sent in the object "Test". Is there anything Im doing wrong?


My Tester class looks like this

public class Tester implements Serializable {
    private String theMessage = "";

    public Tester(String message) {
        theMessage = message;
    }

    public String getText() {
         return theMessage;
    }
}

Upvotes: 1

Views: 1033

Answers (2)

Andremoniy
Andremoniy

Reputation: 34900

It seems, that you had wrapped code-block of socket listener into try...catch statement, where you are using some logger in catch part in an incorrect way: it prints the stacktrace instead of printing the error cause. This is the most probable explanation, why you receive [Ljava.lang.StackTraceElement;....

Indeed your socket-listener code catches some Exception, which you have to print in an appropriate way.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

Try this

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream();
Tester tester0 = new Tester("test")
oos.writeObject(tester0);
oos.close();
System.out.println(tester0.getText());

ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
Tester tester = (Tester) ois.readObject();
System.out.println(tester.getText());

If this doesn't work, you may have a bug in your serialization code.

Upvotes: 2

Related Questions