Serializable与Parcelable实现序列化

Serializable

Serializable是Java所提供的一个序列化接口,实现的时候应该指定对象的serialVersionUID。
在Android Studio如何快速填写UID:

  1. File–>Settings–>Editor–>Inspections–>Java–>Serialization
    issues–>Serializable class without ‘serialVersionUID’ 勾选中该选项即可
  2. 进入实现了Serializable中的类,选中类名,Alt+Enter弹出提示,然后直接导入完成
    实现序列化和反序列化:
public class Student implements Serializable{

    private static final long serialVersionUID = 851965803178397333L;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String adress, String name, int age) {
        this.adress = adress;
        this.name = name;
        this.age = age;
    }

    private String adress;
    private String name;
    private int age;

    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;
    }
}
public class myClass {

    private static Student newStudent;

    public static void main(String[] args) {
        Student student=new Student("谢耀眼",22);
        try {
            ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("cache"));
            out.writeObject(student);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            ObjectInputStream out=new ObjectInputStream(new FileInputStream("cache"));
            newStudent = (Student) out.readObject();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(newStudent.equals(student));

    }
}

输出:false
恢复后的newStudent和student内容完全一样但是两者不是同一个对象。
如果我们不指定serialVersionUID,当对象的结构发生变化之后,就会报异常。

public class Student implements Serializable{

    public Student(String adress, String name, int age) {
        this.adress = adress;
        this.name = name;
        this.age = age;
    }

    private String adress;
    private String name;
    private int age;

    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;
    }
}

将serialVersionUID字段去掉,并且增加了一种新的构造方法。
当反序列化的时候就会报出异常:

java.io.InvalidClassException: com.example.lib.Student; local class incompatible: stream classdesc serialVersionUID = 851965803178397333, local class serialVersionUID = -67645744269838304

注意两点:
静态成员变量属于类,不属于对象,所以不会参与序列化过程
使用transient关键字标记的成员变量不参与序列化过程

Parcelable

这个是Android中的接口,实现这个接口,就可以通过Intent和Binder传递。

public class Student implements Parcelable{
    @Override
    public String toString() {
        return "Student{" +
                "adress=" + adress +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    private Adress adress;
    private String name;
    private int age;

    public Student(Adress adress, String name, int age) {
        this.adress = adress;
        this.name = name;
        this.age = age;
    }

    protected Student(Parcel in) {
        System.out.println("Student.Student");
        adress = in.readParcelable(Adress.class.getClassLoader());
        name = in.readString();
        age = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        System.out.println("Student.writeToParcel");
        dest.writeParcelable(adress, flags);
        dest.writeString(name);
        dest.writeInt(age);
    }

    @Override
    public int describeContents() {
        System.out.println("Student.describeContents");
        return 0;
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            System.out.println("Student.createFromParcel");
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            System.out.println("Student.newArray");
            return new Student[size];
        }
    };
}
public class Adress implements Parcelable {
    private String adress;


    public Adress(String adress) {
        this.adress = adress;
    }

    protected Adress(Parcel in) {
        adress = in.readString();
    }

    public static final Creator<Adress> CREATOR = new Creator<Adress>() {
        @Override
        public Adress createFromParcel(Parcel in) {
            return new Adress(in);
        }

        @Override
        public Adress[] newArray(int size) {
            return new Adress[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(adress);
    }
}
public void Jump(View view){
        Student student=new Student(new Adress("中国"),"yaoyan",22);
        Intent intent=new Intent(this,SecondActiivity.class);
        Bundle bundle=new Bundle();
        bundle.putParcelable("yaoyan",student);
        System.out.println("MainActivity.Jump");
        intent.putExtra("mainActivity",bundle);
        startActivity(intent);
    }
public class SecondActiivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("mainActivity");
        System.out.println("SecondActiivity.onCreate");
        Student yaoyan = bundle.getParcelable("yaoyan");
        System.out.println("yaoyan = " + yaoyan);
    }
}

这里写图片描述
从打印的顺序来看,在对象序列化的时候会调用writeToParcel方法,在跳转后的Activity(SecondActiivity)中,当获取对象时,会调用反序列化方法createFromParcel。

在Android开发艺术探索中提到:
Serializable:使用起来简单但是开销很大,序列化和反序列化过程都需要大量I/O操作。
Parcelable:效率高,是Android推荐的序列化方式,但是操作麻烦。

这里写图片描述

QQ交流群:365473065

参考书籍:
《Android开发艺术探索》
参考链接:
如何导入UID

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值