So I'm making a deep copy of an object using method here (serialise and deserialise).
Before doing the clone, I'll need to initialise a List in the object so that the copy can have it. This is what I did:
Product prod = getProdFromDB();
//initialise someList
prod.getSomeList();
Product copiedProd = clone(prod);
// errors out because it's not copied
copiedProd.getSomeList()
Although I've added prod.getSomeList()
before clone, it doesn't do the job for me.
Interesting thing is, if I run prod.getSomeList()
manually in debugging mode, then copiedProd will have someList in it.
As a stopgap, instead of simply do prod.getSomeList()
, I need to assign it to a variable and use the variable before clone:
List someList = prod.getSomeList();
System.out.println(someList);
I have 2 questions:
- Why is this? My guess is that Java sees that
getSomeList
isn't doing anything so has it removed from compiled code (something done by JIT?) - Apparently
System.out.println(someList)
isn't an elegant way, is there some other ways I can use? (I don't have Hibernate lib in this project so Hibernate::initialise is not an option)
Thanks in advance!
FYI this is the clone method:
private static <T extends Serializable> T clone(T obj) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(bout);
oos.writeObject(obj);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bin);
return (T) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}