如何在列表对象中读取以使用不同的构造函数进行序列化和验证



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

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

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

发生了什么事,是只有实现序列化的类的字段才能写入和读取。

这就是为什么collegeName正确编写和正确阅读的原因,因为它在您的继承类中实现了可序列化的作用。其他字段属于基类,不会这样做。

要么声明您需要在Student中分别序列化的变量,要么使Person也实现序列化。

最新更新