2016-08-04 68 views
0

中只得到特定序列化的領域我有名字和ID的Student類:如何反序列化

import java.io.Serializable; 
public class Student implements Serializable{ 
int id; 
String name; 
public Student(int id, String name) { 
    this.id = id; 
    this.name = name; 
} 
} 

我在下面的方式串行化:

import java.io.*; 
class Persist{ 
public static void main(String args[])throws Exception{ 
    Student s1 =new Student(211,"ravi"); 

    FileOutputStream fout=new FileOutputStream("f.txt"); 
    ObjectOutputStream out=new ObjectOutputStream(fout); 

    out.writeObject(s1); 
    out.flush(); 
    System.out.println("success"); 
} 
} 

在反序列化,如果我不」我想要id回來,我該怎麼辦?需要注意的是,id應該被序列化,所以不使用瞬態或靜態。

+0

爲什麼不你允許使用瞬態? – JavaHopper

+0

覆蓋readObject()。 –

+0

有些人請幫助我senario – binesh

回答

0

您應該遵循定製反序列化,通過Student類中重寫readObject()方法,如下圖所示

Student類

import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.Serializable; 

public class Student implements Serializable 
{ 
    int id; 
    String name; 

    public Student(int id, String name) 
    { 
     this.id = id; 
     this.name = name; 
    } 

    @Override 
    public String toString() 
    { 
     return "[id: " + id + " , name: " + name+ "]"; 
    } 

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { 
     ois.defaultReadObject(); 
     //set those values to their default, which you don't want to retrieve 
     this.id = 0; 
    } 
} 

Tester類

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 

public class Test 
{ 
    public static void main(String args[]) throws Exception 
    { 
     Student s1 = new Student(211, "ravi"); 

     FileOutputStream fout = new FileOutputStream("f.txt"); 
     ObjectOutputStream out = new ObjectOutputStream(fout); 

     out.writeObject(s1); 
     out.flush(); 
     System.out.println("success"); 

     FileInputStream fis = new FileInputStream("f.txt"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 
     s1 = (Student)ois.readObject(); 
     System.out.println(s1); 
    } 
}