如何使用不同的构造函数读取要序列化和反序列化的列表对象?

时间:2017-05-01 01:40:47

标签: java list object serialization constructor

我正在制作代码以将要序列化的对象列表传输到文件中并返回。问题是当我第一次序列化文件时,使用默认构造函数而不是第二个构造函数来实例化对象。

换句话说,输出带有默认值:

0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]
0 N/A N/A 01-01-1980 [UCLA]

但它应该是:

1234 Robert Smith 07-05-1980 [UCLA]
2345 Donald Trump 07-05-1980 [UCLA]
3456 Barack Obama 07-05-1980 [UCLA]

这是我的主要方法:

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // ArrayList list

ArrayList<Student> al = new ArrayList<Student>();
    Date d = new Date(80, 5, 7);
    Student s = new Student("Robert", "Smith", 1234, d, "UCLA");
    Student s2 = new Student("Donald", "Trump", 2345, d, "UCLA");
    Student s3 = new Student("Barack", "Obama", 3456, d, "UCLA");
    al.add(s);
    al.add(s2);
    al.add(s3);

    // serialization test
    FileOutputStream fileOut = new FileOutputStream("StudentList.dat");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(al);
    out.close();
    fileOut.close();

    // deserialization test
    FileInputStream fileIn = new FileInputStream("StudentList.dat");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    ArrayList<Student> a2 = (ArrayList<Student>) in.readObject();
    in.close();
    fileIn.close();

    System.out.println(a2.size());

    for (Student i : a2) {
        System.out.println(i);
    } // for
} // main

由于

编辑:添加学生班

package edu.uga.cs1302.gui;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;


@SuppressWarnings({ "serial", "rawtypes", "deprecation", "unchecked" })
public class Student extends Person implements Serializable {

private String collegeName;

/*
 * public Student() { super(); collegeName = null; } // constructor
 **/
public void setC(String c) {
    collegeName = c;
} // set college

public String getC() {
    return collegeName;
} // get college

public Student(String fName, String lName, int n, Date d, String college) {
    super(fName, lName, n, d);
    collegeName = college;
} // second constructor

public String toString() {
    return super.toString() + " [" + collegeName + "]";
} // to string
} // class

1 个答案:

答案 0 :(得分:1)

正在发生的事情是,只有正在编写和读取实现Serializable的类的字段。

这就是正确编写和读取collegeName的原因,因为它在您继承的类中实现了Serializable。其他字段属于基类,不会这样做。

Student中声明要分别序列化的变量,或者使Person实现Serializable。