Converts a byte array to an object. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte array to an object.

Demo Code


import java.io.*;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] bytesToConvert = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(byteArrayToObject(bytesToConvert));
    }/*from   w ww  .j  ava  2  s  .c o  m*/
    private static final ByteManipulationUtils instance = new ByteManipulationUtils();
    /**
     * Converts a byte array to an object.
     * @param bytesToConvert
     * @return
     */
    public static final <X> X byteArrayToObject(byte[] bytesToConvert) {
        return instance.byteArrayToObjectPrivate(bytesToConvert);
    }
    /**
     * Converts a byte array to an object.
     * @param bytesToConvert
     * @return
     */
    private final <X> X byteArrayToObjectPrivate(byte[] bytesToConvert) {
        X returnedObj = null;
        try {
            DummyClassLoader loader = new DummyClassLoader(
                    ByteManipulationUtils.class.getClassLoader());
            Class<X> tempClass = (Class<X>) loader.dummyDefineClass(null,
                    bytesToConvert, 0, bytesToConvert.length);
            return tempClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            NAPILogHelper.instance.logError(e);
        }

        return returnedObj;
    }
}

Related Tutorials