java 深度拷贝

利用文件操作进行java深度拷贝。

        public static Object copy(Serializable oldObj) {
        Object obj = null;
        try {
            // Write the object out to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
                out.writeObject(oldObj);
                out.flush();
            }

            // Retrieve an input stream from the byte array and read
            // a copy of the object back in.
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream in = new ObjectInputStream(bis);
            obj = in.readObject();
        } catch ( IOException | ClassNotFoundException e ) {
            e.printStackTrace();
        }
        return obj;
    }

你可能感兴趣的:(java 深度拷贝)