一、前言
通过c3p0源码包中的com.mchange.v2.ser.SerializableUtils实现对对象序列化工具类对对象序列化serializeToByteArray处理、二进制字节流deserializeFromByteArray反序列化为对象等常用转换操作。
二、源码说明
package com.mchange.v2.ser;@b@@b@import com.mchange.v1.io.InputStreamUtils;@b@import com.mchange.v1.io.OutputStreamUtils;@b@import java.io.BufferedInputStream;@b@import java.io.BufferedOutputStream;@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.IOException;@b@import java.io.NotSerializableException;@b@import java.io.ObjectInputStream;@b@import java.io.ObjectOutputStream;@b@@b@public final class SerializableUtils@b@{@b@ public static byte[] toByteArray(Object obj)@b@ throws NotSerializableException@b@ {@b@ return serializeToByteArray(obj);@b@ }@b@@b@ /**@b@ * @deprecated@b@ */@b@ public static byte[] serializeToByteArray(Object obj) throws NotSerializableException {@b@ ByteArrayOutputStream baos;@b@ try {@b@ baos = new ByteArrayOutputStream();@b@ ObjectOutputStream out = new ObjectOutputStream(baos);@b@ out.writeObject(obj);@b@ return baos.toByteArray();@b@ }@b@ catch (NotSerializableException e)@b@ {@b@ e.fillInStackTrace();@b@ throw e;@b@ }@b@ catch (IOException e)@b@ {@b@ e.printStackTrace();@b@ throw new Error("IOException writing to a byte array!");@b@ }@b@ }@b@@b@ public static Object fromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {@b@ return deserializeFromByteArray(bytes);@b@ }@b@@b@ /**@b@ * @deprecated@b@ */@b@ public static Object deserializeFromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {@b@ ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));@b@ return in.readObject();@b@ }@b@@b@ public static Object testSerializeDeserialize(Object o)@b@ throws IOException, ClassNotFoundException@b@ {@b@ byte[] bytes = serializeToByteArray(o);@b@ return deserializeFromByteArray(bytes);@b@ }@b@@b@ public static final Object unmarshallObjectFromFile(File file)@b@ throws IOException, ClassNotFoundException@b@ {@b@ ObjectInputStream in = null;@b@ try@b@ {@b@ in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));@b@ return in.readObject();@b@ }@b@ finally {@b@ InputStreamUtils.attemptClose(in);@b@ }@b@ }@b@@b@ public static final void marshallObjectToFile(Object o, File file) throws IOException@b@ {@b@ ObjectOutputStream out = null;@b@ try@b@ {@b@ out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));@b@ out.writeObject(o);@b@ }@b@ finally {@b@ OutputStreamUtils.attemptClose(out);@b@ }@b@ }@b@}