public class Melon implements Serializable { private final String type; private final float weight; // 布局函数,getter,setter}
以及一个Melon的实例:
Melon melon = new Melon("Gac", 2500);
将melon实例序列化为字节数组可以按照以下办法完成:
public static byte[] objectToBytes(Serializable obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream ois = new ObjectOutputStream(baos)) { ois.writeObject(obj); } baos.close(); return baos.toByteArray();}
当然,我们可以利用这个助手来序列化任何其他工具,但对付melon实例,我们这样调用它:

byte[] melonSer = Converters.objectToBytes(melon);
反序列化是通过另一个利用readObject()的助手完成的,如下所示:
public static Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException { try ( InputStream is = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(is)) { return ois.readObject(); }}
我们可以利用这个助手将任何其他工具从字节数组中反序列化,但对付melonSer,我们这样调用它:
Melon melonDeser = (Melon) Converters.bytesToObject(melonSer);
返回的melonDeser规复了初始工具状态,纵然它不是同一个实例。在打包的代码中,您还可以看到一种基于Apache Commons Lang的方法。