If all the objects within the bean implement Serializable
interface, will BeanUtils.cloneBean()
do a deep copy?
Asked
Active
Viewed 4.9k times
24

Jan Nielsen
- 10,892
- 14
- 65
- 119

hop
- 2,518
- 11
- 40
- 56
3 Answers
40
Use SerializationUtils.clone method from the Apache Commons Lang for the deep copy. It copies the entire class hierarchy.
SerializationUtils.clone(object);

Vikas Chowdhury
- 737
- 8
- 15
-
8It should be noted however that this method comes with a much steeper performance penalty. – Thihara Apr 16 '14 at 05:56
9
No, cloneBean()
does shallow copy only. If you want deep copy. You may refer this link which has technique to do deep copy.

Jan Nielsen
- 10,892
- 14
- 65
- 119

kosa
- 65,990
- 13
- 130
- 167
-
1Deep clone over XML - not sure if people actually want that, the approach listed below is a bit better, since it does not use XML but still exploits serialization. – siyb Jul 01 '16 at 12:14
1
There is also another java library which supports both shallow cloning and deep cloning. It offers deep cloning without the need to implement Serializable.

dilanSachi
- 562
- 6
- 14
-
3Link-only answers aren't helpful in the long term, because links tend to become invalid over time. – toolforger Dec 12 '20 at 11:46
-
@toolforger I understand the issue. But what I pointed to was a Github repo and I cannot express it in here in any other way. – dilanSachi Dec 12 '20 at 16:17
-
1The common advice is to at least mention the point of the link, so people know whether it's worth their time to follow the link. It's even better if you can explain what they're doing. Or you can highlight how it's different from other answers (which will give yourself more insight so it's worth doing more than others to follow the link). Finally, there's always the option to remove the answer, because it won't help anybody if it does not interest anybody. – toolforger Dec 13 '20 at 22:42
-
@toolforger actually I have mentioned what the link contains and it's difference. It helped me in my implementation so I thought of mentioning here. – dilanSachi Dec 16 '20 at 14:49
-
You don't mention the library's name (it may be moved to another link), nor the library's approach. – toolforger Dec 17 '20 at 21:26