0

I want to copy an entire object which doesn't implement clone method.

The BeanUtils.copyProperties(obj1, obj2) does the copy however makes the process tedious as we need to register which are the value will be null.

ex:

 ConvertUtils.register(new DateConverter(null), Date.class);
 BeanUtils.copyProperties(emp1, emp2);

where the emp2 will have some date methods where the property might be null..

Assume there might be 100 of properties might be null and we need to just ignore the same..

I need the exact copy of the object.

Could someone suggest the best way or a utility to achieve this?

Thanks.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
user2323036
  • 1,515
  • 5
  • 19
  • 27

2 Answers2

3

You can serialize the object and deserialize it back. Serialization->Deserialization is alternative to deep cloning

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

sanbhat's answer is the only way to achieve 100% clone. Be careful, serialization and deserialization are slow processes.

yogiam
  • 168
  • 7
  • Thanks for the details...if the process is slow is there is any alternatives...such as Cloner cloner=new Cloner(); Object cloned = cloner.deepClone(someObject); (OR) // or with Apache Commons cloned = org.apache.commons.lang. SerializationUtils.clone(someObject); – user2323036 Aug 19 '13 at 12:15
  • AFAIK, if you want 100% cloning, all the libs drill down to serialization. I dont see any magic happening there :) – yogiam Aug 27 '13 at 13:46