I have a client/server program, and I'm sending objects through ObjectOutputStream via writeObject() and readObject().
The object I'm sending is class consisting of a couple of fields, and another object inside (let's call the outer object Wrapper and the inner Inner. Both the custom objects implement serializable.
The first time I send the Wrapper over, everything works flawlessly. Everything stored in both Wrapper, Inner and all the fields serialize and deserialize without problems.
However, when the client then modifies the Inner class, puts it in the Wrapper, and sends it one more time, the Inner instance received by the server, is identical to the one received the first time around.
My client:
Inner inner = new Inner();
inner.setValue("value");
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(new Wrapper(inner));
Server:
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Wrapper wrapper = (Wrapper) in.readObject();
String value = wrapper.getInner().getValue();
Client then modifies the Inner class (same instance as before) with a DIFFERENT string (ie. containing other letters then the first one):
inner.setValue("newValue");
out.writeObject(new Wrapper(inner));
However, when I look at the inner.getValue() on the server, it has not changed and is still equal to "value".
I solved this, by making a hard copy of the inner class, before sending it over:
Inner newInner = new Inner();
newInner.setValue("newValue");
out.writeObject(new Wrapper(newInner));
The new value now is updated as it should.
Why does serialization work this way?