Package org.jboss.mx.util

Source Code of org.jboss.mx.util.SerializationHelper

package org.jboss.mx.util;

import org.jboss.mx.server.ObjectInputStreamWithClassLoader;

import java.io.*;

/**
* SerializationHelper
*
* @author Jeff Haynie
*/
public class SerializationHelper
{
    /**
     * deserialize, using the current Thread Context classloader
     *
     * @param byteArray
     * @return deserialized object
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deserialize(byte[] byteArray)
            throws IOException, ClassNotFoundException
    {
        return deserialize(byteArray,Thread.currentThread().getContextClassLoader());
    }
    /**
     * deserialize an object using a specific ClassLoader
     *
     * @param byteArray
     * @param cl
     * @return deserialized object
     * @throws java.io.IOException
     * @throws ClassNotFoundException
     */
    public static Object deserialize(byte[] byteArray, ClassLoader cl)
            throws IOException, ClassNotFoundException
    {
        if (byteArray == null)
        {
            return null;
        }
        if (byteArray.length == 0)
        {
            return null;
        }
        try
        {
            if (cl==null)
            {
                // use system loader
                cl = SerializationHelper.class.getClassLoader();
            }
            ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(byteArray);
            ObjectInputStream objectinputstream = new ObjectInputStreamWithClassLoader(bytearrayinputstream,cl);
            Object obj = objectinputstream.readObject();
            return obj;
        }
        catch (OptionalDataException optionaldataexception)
        {
            throw new IOException(optionaldataexception.getMessage());
        }
    }

    /**
     * serialize an object
     *
     * @param obj
     * @return serialized object
     * @throws java.io.IOException
     */
    public static byte[] serialize(Object obj)
            throws IOException
    {
        ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
        ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream);
        objectoutputstream.writeObject(obj);
        return bytearrayoutputstream.toByteArray();
    }
}
TOP

Related Classes of org.jboss.mx.util.SerializationHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.