(1)永久的保存對象,將對象數據保存在文件、磁盤或者數據庫中 。數據庫
(2)經過序列化操做將對象數據在網絡上進行傳輸 。bash
(3)將對象序列化以後在進程間進行傳輸 。網絡
(4)在安卓中使用 Intent 進行傳輸時候,數據類型較爲複雜的須要進行序列化操做 。ide
public class Mybox4 implements Serializable {
private String name;
private String age;
public Mybox4(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Mybox4{" +
"name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } 複製代碼
經過上述代碼能夠看出,使用 Serializable 的時候比較簡單,只須要實現 Serializable 接口便可,這樣就告訴程序這個類是能夠被序列化的。ui
下面看下如何實現對象的序列化與反序列化:this
Mybox4 mybox4 = new Mybox4("keven", "27");
File file = new File("box.out");
//序列化
FileOutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(mybox4);
objectOutputStream.close();
//反序列化
FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
Mybox4 o = (Mybox4) inputStream.readObject();
inputStream.close();
System.out.println(o.toString());
複製代碼
輸出爲:spa
Mybox4{name='keven', age='27'}
複製代碼
Parcelable 是 Android 特有的序列化方式,他的實現相對 Serialiable 來講更加複雜一點。code
Parcelable 內部包裝了可序列化的數據,序列化功能由 writeToParcel 方法完成,反序列化由 CREATOR 完成。對象
public class Mybox4Par implements Parcelable {
private String name;
private String age;
public Mybox4Par(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Mybox4Par{" +
"name='" + name + '\'' + ", age='" + age + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(age); } public static final Parcelable.Creator<Mybox4Par> CREATOR=new Creator<Mybox4Par>() { @Override public Mybox4Par createFromParcel(Parcel source) { return new Mybox4Par(source); } @Override public Mybox4Par[] newArray(int size) { return new Mybox4Par[size]; } }; public Mybox4Par(Parcel in){ name=in.readString(); age=in.readString(); } } 複製代碼
上述就是實現了 Parcelable 接口,並重寫方法,咱們看下如何使用:接口
//第一個Activity
Mybox4Par mybox4Par=new Mybox4Par("keven","25");
Bundle bundle=new Bundle();
Intent intent=new Intent(this,MyViewActivity.class);
bundle.putParcelable("box",mybox4Par);
intent.putExtras(bundle);
startActivity(intent);
複製代碼
//第二個Activity
Intent intent=getIntent();
Bundle extras = intent.getExtras();
Mybox4Par box = extras.getParcelable("box");
Log.e("box",box.toString());
複製代碼
Serializable 使用簡單可是開銷很大,序列化與反序列化須要大量的 I/O 操做,通常用於將對象序列化到存儲設備中,或序列化後經過網絡傳輸;
Parcelable 使用稍微麻煩點,可是效率高,主要用在內存序列化上。