Java实体类对象序列化成byte[]字节数组的方法,需要实体类实现java.io.Serializable接口之后才可以将实体列对象ByteArrayOutputStream的形式转化为字节数组进行传输,下面是代码,包含了byte[]字节数组反序列化方法:
import java.io.*; public class SerializeUtils { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); } }
如果你的java实体列实现了Serializable序列化接口,代码如下:
import java.io.Serializable; public class LoginMessage implements Serializable { private static final long serialVersionUID = 1L; }
则可以通过我们的java对象序列化与反序列化方法工具类了:
//序列化对象为byte字节数组 byte[] bys = SerializeUtils.serialize(new LoginMessage()); //反序列化byte字节数组为对象 LoginMessage loginMsg = (LoginMessage)SerializeUtils.deserialize(bys);