1. 程式人生 > >java序列化注意點

java序列化注意點

1.顯示申明serialVersionUID可以避免物件不一致。因為在jvm反序列化時,會比較資料流中的serialVersionUID與類的    serialVersionUID是否相同,若相同則認為類沒有發生變化,可以把資料流load為例項物件;若不同,則拋異常  InnalidClassException.
 2.避免用序列化類在建構函式中為final變數賦值。反序列化時final變數在以下情況不會重新賦值。
1.通過建構函式為其賦值(反序列化時不會執行建構函式)
 2.通過方法返回值為其賦值 
3.final修飾的屬性不是基本型別。(基本型別包括:8種基本型別,陣列,未使用new生成的字串)

注:物件流不序列化static或transient屬性。

4.自定義序列化,只需在被序列化的欄位裡新增writeObject及readObject方法即可,例如:

public class User implements Serializable{
private static final long serialVersionUID = 1L;
     private  String name="YY";
     private String age="123";
     
public User(){
System.out.println("+++++++");
}
     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;
}


private final   String  id=new String("222");


public String getId() {
return id;
}

//自定義要序列化的欄位
private void writeObject( ObjectOutputStream oos) throws IOException{

   oos.defaultWriteObject();
   oos.writeBytes(this.getName());
   oos.writeInt(Integer.parseInt(this.getId()));
}
//自定義讀取序列化的欄位
private void readObject(ObjectInputStream ois) throws  IOException, ClassNotFoundException{

ois.defaultReadObject();
System.out.println(ois.readByte());
System.out.println(ois.readInt());
}


private static String  filePath = "E:/Program/MyTest/files/serial.txt";
public static  File getFile(){
return new File(filePath);
}
}