Serializable是 序列化的意思,表示将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上进行传输,也可以存储到本地。至于序列化的方式,只需要让一个类实现该接口即可。

eg:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Student implements Serializable {
public static final long serialVersionUID = 1L;
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不写同样可以实现序列化,serialVersionUID实现序列化时,会把当前类的serialVersionUID写入序列化的文件中,当反序列化时系统会去检测文件中的serialVersionUID,看它是否和当前类的serialVersionUID是否一致,如果一致则可以成功反序列化,否则则说明当前类和序列化的类相比发生了某些变化,这时候反序列化失败。一般来说,我们都是要手动指定serialVersionUID的值。此外静态从成员变量属于类不属于对象,所以不会参与序列化的过程,其次用transient关键字标记的成员不参与序列化过程。

此外我们还可以使用Parcelable接口来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Person implements Parcelable{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}

protected Person(Parcel in) {
//读取name 和 age
name = in.readString();
age = in.readInt();
}

public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
//实现反序列化
return new Person(in);
}

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

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

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

@Override
public void writeToParcel(Parcel dest, int flags) {
//序列化 写出name 和 age
dest.writeString(name);
dest.writeInt(age);
}
}

以上具体的几个方法说明如下:

createFromParcel(Parcel in):从序列化的对象中创建原始对象

newArray(int size):创建指定长度的原始数组

Person(Parc el in):从序列化的对象中创建原始对象

writeToParcel(Parcel out,int flags):将当前对象写入序列化结构中,其中flags标识由两种值:0和1。为1标识当前对象需要作为返回值返回,不能立即释放资源,几乎所有情况为0;

describeContents:返回当前对象内容描述。如果含有文件描述符,返回1,否则返回0,几乎所有的情况都返回0

w相比较而言,Serializable是java中的序列化接口,虽然使用简单,但是开销很大,序列化和反序列化要实现大量的II/O操作。而Parcelable是Android中的序列化方式,因此更适合用在Android平台上,虽然使用麻烦,但是效率很高。

本文地址: http://www.yppcat.top/2019/03/12/安卓序列化/