0

Suppose, we've got a very simple object:

import java.lang.reflect.*
class Test{
    Oject o;
    Method m;
    Field f;
    ...
    Test testObj = new Test();
}

I need to make a deep copy of testObj. Unfortunately, Object, Method and Field classes are not serializable. But is there a standard way, a workaround or any other way to make the copy have them?

I would greatly appreciate a code sample since general guiding (as in this topic) is too confusing for a newbie like me.

Community
  • 1
  • 1
Vic
  • 211
  • 2
  • 9
  • It is probably covered in http://stackoverflow.com/questions/25472281/how-to-make-deep-copy-of-java-object-without-using-serialization . – Artur Biesiadowski Apr 27 '16 at 13:51
  • I'm not sure what serializable has to do with this problem. You can create a deep copy of testObj using reflection to recursively reflect over each value. – William Morrison Apr 27 '16 at 14:53
  • @William Morrison What do you mean? Can you please go into details or give a link to an example? – Vic Apr 27 '16 at 17:09
  • 1
    http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance This question gives some external tools which can create deep clones of objects using reflection. I see now why you're considering serialization. I do not suggest serializing and unserializing an object to create a deep copy. @Vic – William Morrison Apr 27 '16 at 17:43
  • @Vic was this helpful? Do you have any other questions I can help you with? – William Morrison Apr 28 '16 at 22:38
  • @WilliamMorrison Thank you for your time and input. Well, the tools that rely on serialization (like SerializationUtils and Kryo) seem to be inapplicable here and the only external tool based on reflection (Java Deep Cloning Library) that could do the job is based on the Unsafe class and employs forbidden method (getCallerClass). What would you suggest then if not serialization? – Vic Apr 29 '16 at 07:58
  • I'm not sure why reflection based tools are inapplicable. What exact object can you not create a deep copy of using reflection? If the exact object you're reflecting over is `Method`, `Field`, etc. the only real solution is the one you've linked already in your question. – William Morrison Apr 29 '16 at 14:44
  • @WilliamMorrison They are applicable in general but the only such tool mentioned (Java Deep Cloning Library) is not working anymore. I see your point, but then I can't figure out how to use that solution (linked in my question) without an example. – Vic Apr 29 '16 at 18:14

0 Answers0