Deep cloning articles a lot, here is recommended Java enhancement-object cloning (replication).
The above article is clear-organized, at a glance, but recently encountered in the project of the actual problem is that the object is to be cloned with a total of 207 subclass parent, regardless of the above two ways, it is necessary to modify the class file, more cumbersome.
So we try Spring's beanutils.copyproperties and prove that the Copyproperties method is not used for deep cloning. Finally holding the mentality of the attempt to use Jackson, what interface is not realized, even succeeded.
Codemaven
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
Realize
@SuppressWarnings("all") publicstaticdeepClonethrows IOException { if (null == t) { returnnull; } newObjectMapper(); byte[] bytes = objectMapper.writeValueAsBytes(t); return (T) objectMapper.readValue(bytes, t.getClass()); }
Problem
Although generics are used here, it is not possible to clone all objects, such as the List<Person>
--person type is a custom class--The returned type becomes List<LinkedHashMap<String,Object>>
, so this method only fits into a single object.
Java Basics-Deep cloning supplement