Java序列化/反序列化

203 阅读1分钟

序列化

序列化:将对象转换成二进制串的过程

反序列化:将二进制串转换成对象的过程 对象并不能直接存储在设备和直接网络传输,只能通过二进制串来存储和传输。如果对象转换成二进制串就可以跨平台的被使用。 **序列化规则:**对象和二进制串的转换和解析并不是随意,它们必须有一套规则来解析,常有的序列化协议有:XML、JSON、SOAP

JAVA序列化

JAVA序列化的类需要实现Serializable接口,通过ObjectOutputStream实现序列化,通过ObjectInputStream实现反序列化。如果类没有实现Serializable接口进行序列化会报错。

序列化二进制串:

      Student student = new Student();
      student.setName("hai");
      student.setAge(23);
      student.setScore(473);
      try {
          FileOutputStream fileOutputStream = new FileOutputStream(new File("student.txt"))
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
          objectOutputStream.writeObject(student);
          objectOutputStream.close();
          fileOutputStream.close();
      } catch (Exception e) {
          e.printStackTrace();
      }

反序列化对象:

     try {
          FileInputStream fileInputStream = new FileInputStream(new File("student.txt"))
          ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
          Student student = (Student) objectInputStream.readObject();
          objectInputStream.close();
          fileInputStream.close();
      } catch (ClassNotFoundException | FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }

其中被statictransient修饰的变量不会参与到序列化中。

serialVersionUID 这个是序列化版本id,它是通过类名、属性等信息自动生成的,如果类中有改动,serialVersionUID就会改变。如果反序列化时,serialVersionUID版本不同就会反序列化失败。 我们也可以在类中写死serialVersionUID,但是反系列化时发现属性对不上时也会失败。反序列化是通过反射无参构造函数生成对象,然后把值写入反射的对象中。