java序列化&反序列化

序列化反序列化代码示例

package com.test.serialize;

public class Person{
    protected String name;
    protected int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
package com.test.serialize;

import java.io.Serializable;

public class Student extends Person  implements Serializable {
    private static final long serialVersionUID = 1L;

    private static String id = "5420114874123822410";
    double score;
    private transient String initDate;

    public Student(String name, int age, double score, String initDate) {
       super(name,age);
        this.score = score;
        this.initDate = initDate;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Student{");
        sb.append("score=").append(score);
        sb.append(", initDate='").append(initDate).append('\'');
        sb.append(", name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}
package com.test.serialize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class App {

    /**
     * 序列化
     * @param person
     * @param path
     * @throws Exception
     */
    private static void serialize(Student person, String path) throws Exception{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
        oos.writeObject(person);
        oos.close();
    }

    /**
     * 反序列化
     * @param path
     * @throws Exception
     */
    private static Object deserialize(String path) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
        Object obj = ois.readObject();
        ois.close();
        return obj;
    }
    public static void main(String[] args) throws Exception {
        String path = "./tmp/object";
        Student student = new Student("zhangsan",23,99.5,"20180410");

        System.out.println(student);
        serialize(student,path);
        Student deStudent = (Student) deserialize(path);
        System.out.println(deStudent);
    }
}

序列化ID

虚拟机是否允许反序列化,不仅取决于类路径和功能代码是否一致,一个非常重要的一点是两个类的序列化 ID 是否一致,只有ID相同时,才有可能被反序列化成功

静态变

序列化保存的是对象的状态,静态变量属于类的状态,因此 序列化并不保存静态变量。

子类实现Serializable接口,父类不实现Serializable

  • 序列化时,只序列化子类。
  • 反序列化时,必须保证父类有默认的无参构造方法;父类属性填充默认值。

transient关键字

  • 被transient修饰的变量,不被序列化。
  • 反序列化时,自动填充默认值。

参考:https://www.cnblogs.com/wxgblogs/p/5849951.html

猜你喜欢

转载自blog.csdn.net/believe2017slwx/article/details/79884148