如何在反序列化期间仅获取特定的序列化字段

时间:2016-08-04 18:57:20

标签: java serialization

我有一个名为name的学生班:

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应该被序列化,所以不要使用transient或static。

1 个答案:

答案 0 :(得分:0)

您应该通过覆盖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;
    }
}

测试人员类

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);
    }
}