clutching on to my final attributes...

V

VisionSet

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
}
}
 
V

VisionSet

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
}
}
 
P

Piotr Kobzda

VisionSet said:
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 +"]";
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top