java memory object clone

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @Desc 对象clone
*/
public class DeepCloneTool {

@SuppressWarnings("unchecked")
public static <T> T clone(T source) {
try {
// 将对象写到流里
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut;

objOut = new ObjectOutputStream(byteOut);

objOut.writeObject(source);
// 从流里读出来
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream objInput = new ObjectInputStream(byteIn);
return (T) objInput.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}

}

}

Guess you like

Origin www.cnblogs.com/luyang08/p/11222454.html