集册 Java实例教程 通过XMLDecoder深度复制Java Bean

通过XMLDecoder深度复制Java Bean

欢马劈雪     最近更新时间:2020-01-02 10:19:05

493
通过XMLDecoder深度复制Java Bean
/** 来自 NowJava.com - 时代Java**/

//package com.nowjava;

import java.beans.XMLDecoder;

import java.beans.XMLEncoder;

import java.io.*;


public class Main {

    public static <T> T deepCopy(T src) {

        byte[] bytes = xmlEncode(src);

        return (T) xmlDecode(bytes);

    }


    public static byte[] xmlEncode(Object bean) {


        ByteArrayOutputStream os = new ByteArrayOutputStream(16384);

        try (XMLEncoder e = new XMLEncoder(os)) {

            e.writeObject(bean);

        }

        return os.toByteArray();

    }

    /** from 
    N o w J a v a . c o m - 时  代  Java**/

    public static Object xmlDecode(byte[] bytes) {


        Object obj;

        InputStream is = new ByteArrayInputStream(bytes);

        try (XMLDecoder d = new XMLDecoder(is)) {

            obj = d.readObject();

        }

        
展开阅读全文