理解序列化和反序列化对理解面向对象有很大的帮助。举例如下,序列化格式自己定义:
我们有两个类,动物,人,。
人继承动物。
其中:
人的属性有:name(名称),phoneNum(手机号码)等
人的方法有:serialize(),deserialize()
动物的属性有:mood(情绪) sex(性别)等
动物的方法有:serialize(),deserialize()
如下为代码:
动物:
public class Animal(){
private String mood;
public String serializeContent;
public String getMood(){
return mood;
}
public void setMood(Sting strMood){
this.mood = strMood;
}
public String serialize(){
return serializeContent = mood;
}
public void deserialize(String strContent){
this.mood = strContent.split(";")[0];
}
}
人:
public class person{
private String name;
private String phoneNum;
public person(){}
public person(String strName, String strPhoneNum){
this.name = strName;
this.phoneNum = strPhoneNum;
}
public String serialize(){
super.serialize();
super.serializeContent = super.serializeContent + ";" + name + "," + phoneNum;
}
public void deserialize(String strContent){}
super.deserialize(strContent);
this.name = strContent.split(";").split(",")[0];
this.phoneNum = strContent.split(";").split(",")[1];
}
public class TestDemo{
public static void main(String[] args){
Animal animal = new Person(vid, 12345678900);
animal.setMood("高兴");
animal.serialize();
System.out.println(animal.serializeContent);//输出_____高兴;vid,12345678900
String strContext = serializeContent;
Person person = new Person();
person.deserialize(strContext);
System.out.println(person.name);//输出vid
System.out.println(person.phoneNum);//输出12345678900
System.out.println(person.getMood());
}
}