deep Copy Java Bean via XMLDecoder - Java Reflection

Java examples for Reflection:Java Bean

Description

deep Copy Java Bean via XMLDecoder

Demo Code


//package com.java2s;
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);
    }/* w  w w  . j ava 2 s .c  om*/

    public static byte[] xmlEncode(Object bean) {

        ByteArrayOutputStream os = new ByteArrayOutputStream(16384);
        try (XMLEncoder e = new XMLEncoder(os)) {
            e.writeObject(bean);
        }
        return os.toByteArray();
    }

    public static Object xmlDecode(byte[] bytes) {

        Object obj;
        InputStream is = new ByteArrayInputStream(bytes);
        try (XMLDecoder d = new XMLDecoder(is)) {
            obj = d.readObject();
        }
        return obj;
    }

    public static <T> T xmlDecode(byte[] bytes, Class<T> clazz) {
        return (T) xmlDecode(bytes);
    }
}

Related Tutorials