Java中如何将对象转换为字节码Bytes
程序员文章站
2022-03-24 17:52:00
...
首先,随便创建一个类 test ,内容如下
package com.company;
import java.io.Serializable;
public class test implements Serializable {
public String hello(){
return "hello,word!";
}
}
然后创建 bytestoarrey 类,内容如下
package com.company;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class bytestoarrey implements Serializable {
public static void main(String[] args) throws Exception {
test t = new test();
byte[] bufobject = getBytesFromObject(t);
for(int i=0 ; i<bufobject.length ; i++) {
System.out.print(bufobject[i] + ",");
}
}
public static byte[] getBytesFromObject(Serializable obj) throws Exception {
if (obj == null) {
return null;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bo);
oos.writeObject(obj);
return bo.toByteArray();
}
}
运行结果如下: