1、什么是序列化和反序列化
序列化:把对象转换为字节序列的过程。
反序列化:把字节序列恢复成对象的过程。
2、被序列化的类需要实现serializable接口,只是为了标注该对象是可以被序列化的,并没有需要实现的方法。
3、示例:
新建Student类
import java.io.Serializable;public class Student implements Serializable{ private String name; private int age; private static final long serialVersionUID = 1L; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
新建转换工具类SerializeUtils:
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class SerializeUtils { public byte[] Serialize(Object object) { ByteArrayOutputStream byteArrayOutPutStream = new ByteArrayOutputStream(); try { ObjectOutputStream objectOutPutStream = new ObjectOutputStream(byteArrayOutPutStream); //将对象写入到字节数组中进行序列化 objectOutPutStream.writeObject(object); return byteArrayOutPutStream.toByteArray(); }catch (IOException e) { e.printStackTrace(); } return null; } public Object deSerialize (byte[] bytes) { //将二进制数组导入字节数据流中 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); try { //将字节数组留转化为对象 ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); return objectInputStream.readObject(); }catch (IOException e) { e.printStackTrace(); }catch (ClassNotFoundException e) { e.printStackTrace(); } return null; }}
新建测试类test_serializable:
public class test_serializable { public static void main(String[] args) { SerializeUtils serializeUtils = new SerializeUtils(); Student student = new Student(); student.setName("kobe"); student.setAge(20); byte[] serializObject = serializeUtils .Serialize(student); System.out.println(serializObject); Student e = (Student)serializeUtils.deSerialize(serializObject); System.out.println("Name: " + e.getName()+",Age: " + e.getAge()); }}