Java将对象Object转换成Byte字节数组的代码如下:
/**
* @from www.ityuan.com
* @Description: Java将对象Object转换成Byte字节数组
*/
public class ObjectToByteTester implements Serializable {
private static final long serialVersionUID = 932872837809539736L;
public static void main(String[] args) throws IOException {
System.out.println("Bytes字节长度:"+objectToBytes(new ObjectToByteTester()).length);
}
public static byte[] objectToBytes(final Serializable object) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
return baos.toByteArray();
} finally {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
}
}
}
执行结果如下:
Bytes字节长度:49