美文网首页Java笔记
Java-使用序列化拷贝对象

Java-使用序列化拷贝对象

作者: 妍倩倩 | 来源:发表于2016-09-01 17:06 被阅读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;
        }
    }
    

    相关文章

      网友评论

        本文标题:Java-使用序列化拷贝对象

        本文链接:https://www.haomeiwen.com/subject/vcxhettx.html