方法一(可行)
序列化的方式可以实现对象深拷贝,但是对象必须实现Serializable接口
/**
* 使用对象的序列化进而实现深拷贝
* @param obj
* @param <T>
* @return
*/
private <T extends Serializable> T clone(T obj) {
T cloneObj = null;
try {
ByteOutputStream bos = new ByteOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
cloneObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return cloneObj;
}
上述示例摘自
方法二(不可行)
通过新建一个Map,然后循环遍历现有map,将map元素加入到新Map的方式,不可行
public static Map<String, Object> cloneByIterator(HashMap<String, Object> goods) {
Map<String, Object> synGoods = new HashMap<>();
for (Map.Entry<String, Object> e : goods.entrySet()) {
synGoods.put(e.getKey(), e.getValue());
}
return synGoods;
}
在项目中使用方法一后,idea打包会出现报错,
报错信息类似(com.sun.xml.internal.messaging.saaj.util不存在)
这时修改pom文件在spring-boot-maven-plugin后面添加maven-compiler-plugin
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<verbose/>
<bootclasspath>${java.home}/lib/rt.jar${path.separator}${java.home}/lib/jce.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>