Java笔记

Java-使用序列化拷贝对象

2016-09-01  本文已影响6人  妍倩倩
public class CloneUtils<T extends Serializable> {
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        T cloneObje = null;
        
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            
            bais = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bais);
            try {
                cloneObje = (T) ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                bais.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cloneObje;
    }
}
上一篇下一篇

猜你喜欢

热点阅读