在copy 对像时,发现改变copy对象的属性值时,都会改变原值,方法如下:
List a ;//a为方法参数中传进来的list;
方法1:
List b = new ArrayList(a);
方法2:
List b = new ArrayList(Arrays.asList(new A[a.size()]));
Collections.copy(b, a);
以上方法copy完毕后,经测试都会改变原list的对象属性值,放弃;
使用以下方法解决了此问题
/**
* list中的对象必须实现序列化接口 执行序列化和反序列化 进行深度拷贝
* @param srcList
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
private List deepCopy(List srcList) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(srcList);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
List destList = (List) in.readObject();
return destList;
}
根据的2015年11月发现的序列化漏洞修改为:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.struts2.ServletActionContext;
import org.nibblesec.tools.SerialKiller;
/**
* list中的对象必须实现序列化接口 执行序列化和反序列化 进行深度拷贝
* @param srcList
* @return
* @throws IOException
* @throws ClassNotFoundException
* @throws ConfigurationException
*/
@SuppressWarnings("unchecked")
private List deepCopy(List srcList) {
List destList = null;
ByteArrayOutputStream byteOut = null;
ObjectOutputStream out = null;
ByteArrayInputStream byteIn = null;
ObjectInputStream ois = null;
try {
byteOut = new ByteArrayOutputStream();
out = new ObjectOutputStream(byteOut);
out.writeObject(srcList);
byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ois = new SerialKiller(byteIn, "config/serialkiller.conf");
//原方法放弃
// ObjectInputStream in = new ObjectInputStream(byteIn);
// destList = (List) in.readObject();
destList = (List) ois.readObject();
} catch (IOException e) {
LOGGER.error("对象中包含没有继承序列化的对象: " + e.getMessage());
} catch (ConfigurationException e) {
LOGGER.error("对象中包含没有继承序列化的对象: " + e.getMessage());
} catch (ClassNotFoundException e) {
LOGGER.error("对象中包含没有继承序列化的对象: " + e.getMessage());
}
finally{
try {
if(ois != null){ois.close();ois =null;}
if(byteIn != null){byteIn.close();byteIn = null;}
if(out !=null ){out.close();out = null;}
if(byteOut != null ){byteOut.close(); byteOut = null;}
} catch (IOException e) {
LOGGER.error("对象关闭失败: " + e.getMessage());
}
}
return destList;
}