【问题标题】:How to read in list objects to be serialized and deserialized using a different constructor?如何使用不同的构造函数读取要序列化和反序列化的列表对象?
【发布时间】:2017-09-28 12:27:01
【问题描述】:

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

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

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

【问题讨论】:

  • 显示您的Student 课程。
  • @shmosel 添加了它
  • 你可能想看看link
  • 发布Person 类。
  • @SaurabhShirodkar Shirodakar 我想通了。我没有在 Person 类中实现 Serializable 。感谢您的链接。

标签: java list object serialization constructor


【解决方案1】:

发生了什么,只有实现 Serializable 的类的字段被写入和读取。

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

要么在Student 中单独声明要序列化的变量,要么让Person 也实现Serializable。

【讨论】:

  • 感谢详细解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
相关资源
最近更新 更多