I have code like below.
When I deserialize my Parent object my 2 references to my 'A' object will
become independent references to separate objects.
My work round is as below, with the dual updates to the 'A' object, but that
update is not trivial and it seems daft to do it twice.
When I get an update I could recopy accross the reference to 'A' but that
destroys my 'final' elegance.
What are my options / usual solutions to this kind of thing?
TIA,
Mike W
class Parent {
private final Child c;
private final A a;
Parent() {
a = new A();
c = new Child(a);
}
void update(Parent p) {
a.update(p.a);
c.update(p.c);
}
}
class Child {
private final A a;
Child(A _a) {
a = _a;
}
void update(Child c) {
a.update(c.a); // don't want to do this
}
}
Should I just change Child to this?
class Child {
private A a; // now not final
Child(A _a) {
a = _a;
}
void update(Child c) {
a = c.a; // replace reference
}
}
--
Mike W
> When I deserialize my Parent object my 2 references to my 'A' object will
> become independent references to separate objects.
It seems like your serialization / deserialization mechanism failure.
> What are my options / usual solutions to this kind of thing?
Use Java standard (built-in) Serialization.
Sample code provided below produce the following output:
Parent@6b97fd [c=Child@1c78e57 [a=A@5224ee], a=A@5224ee]
Parent@efd552 [c=Child@19dfbff [a=A@10b4b2f], a=A@10b4b2f]
As you can see, before serialization and after deserialization there is
only one A class instance in Parent's objects tree.
Regards,
piotr
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
Parent p = new Parent();
System.out.println(p);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(p);
oos.close();
ByteArrayInputStream bais = new
ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
p = (Parent) ois.readObject();
System.out.println(p);
}
}
class A implements Serializable {
}
class Parent implements Serializable {
private final Child c;
private final A a;
Parent() {
a = new A();
c = new Child(a);
}
public String toString() {
return super.toString() +" [c="+ c +", a="+ a +"]";
}
}
class Child implements Serializable {
private final A a;
Child(A _a) {
a = _a;
}
public String toString() {
return super.toString() +" [a="+ a +"]";
}
}