首先,创建要转换的类 test ,内容如下。注意,该类一定要实现序列化

package com.company;
import java.io.Serializable;

public class test implements Serializable {
String name="test";
public String example(){
return "hello,word!";
}
}

然后创建 object_array 类,内容如下

package com.company;

import java.io.*;
public class object_array {
public static void main(String[] args) throws Exception {
test t =new test();
System.out.print ( "java class对象转换为字节数组:\n" );
byte[] bufobject = getBytesFromObject(t);
for(int i=0 ; i<bufobject.length ; i++) {
System.out.print(bufobject[i] + ",");
}
System.out.println ("\n");
System.out.print ("字节数组还原对象:\n");
Object object1 = null;
object1=deserialize(bufobject);
test t1 =(test)object1;
System.out.println ("调用对象的成员变量:"+t1.name);
System.out.println ("调用对象的成员函数:"+t1.example());
}
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();
}
public static Object deserialize(byte[] bytes) {
Object object = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);//
ObjectInputStream ois = new ObjectInputStream(bis);
object = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return object;
}
}

运行结果如下:

Java中对象和字节数组互转_java

本文项目代码:链接: https://pan.baidu.com/s/1jaqBdvcrAPuqqdUxJJKKvQ 提取码: v8ij