import java.io.Serializable;
public class Person implements Serializable {
//如果不定义,系统会自动生成一个
//一般来说,我们需要手动指定,当反序列化时,如果类发生了改变,比如增加或删除了某些成员变量,系统重新计算serialVersionUID的值
//这个时候,保存在文件中的那个对象的serialVersionUID值和当前类的serialVersionUID值已经不一致了,会导致序列化失败
//如果你修改了类名,或者成员变量的数据类型,也是会序列化失败,因为结构已经发生了根本性的改变
private final static long serialVersionUID = 1L;
//transient和static修饰的成员变量不会参与序列化
private transient int verson;
public String name;
public int age;
}
public static void main(String[] args){
Person person = new Person();
person.name = "miku";
person.age = 18;
try {
//将对象保存到本地文件
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\person.obj"))) {
objectOutputStream.writeObject(person);
}
//将保存到本地文件的对象反序列化,转换成可实际操作的对象
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\person.obj"))) {
Person personWrite = (Person)objectInputStream.readObject();
System.out.println("===========反序列化=============");
System.out.println("name:" + personWrite.name);
System.out.println("age:" + personWrite.age);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public interface Parcelable {
public void writeToParcel(Parcel dest, @WriteFlags int flags);
public interface Creator<T> {
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
public interface ClassLoaderCreator<T> extends Creator<T> {
public T createFromParcel(Parcel source, ClassLoader loader);
}
}
1.Parcelable的使用
public class Person implements Parcelable {
public String name;
public int age;
public int type;
public Object obj;
public Person user;
public Person(){
}
//出来实现接口提供的方法,还需要定义一个Parcel参数的构造函数CREATOR 调用
//读取的顺序要和写入的顺序一致,比如 type,name,age,那么writeToParcel()方法
//中的顺序也要一致
private Person(Parcel in) {
type = in.readInt();
name = in.readString();
age = in.readInt();
user = in.readParcelable(Thread.currentThread().getContextClassLoader());
}
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];
}
};
//默认返回0就可以了
//官方文档:https://developer.android.com/reference/android/os/Parcelable.html#CONTENTS_FILE_DESCRIPTOR
@Override
public int describeContents() {
return 0;
}
//将数据写入到Parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(type);
dest.writeString(name);
dest.writeInt(age);
dest.writeParcelable(user,0);
}
}
Person person = new Person();
person.name = "miku";
person.age = 16;
person.type = 1;
//直接通过intent传递
Intent intent = new Intent(this,xxx.class);
intent.putExtra("user", person);
startActivity(intent);
xxxActivity.java
Person person = (Person) getIntent().getParcelableExtra("user")