首页 > 解决方案 > ObjectInputStream - 读取对象 - 有没有办法阻止调用无参数超类构造函数?

问题描述

我正在使用 FileIOStreams 和 ObjectIOStreams 将 PreferedCustomer 对象写入 .dat 文件。我正在练习继承,所以有一个简单的类层次结构。

PreferredCustomer.java 继承自 Customer.java

Customer.java 继承自 Person.java。

当我从 .dat 文件中读取我的 PreferredCustomer 对象时,它调用 Person.java 无参数构造函数并将 Name、Address 和 PhoneNumber 字段设置为“”。如何防止它调用重置字符串值的无参数构造?

我将项目托管在 github 上。 https://github.com/davidmistretta/CustomerObjectDAT

我认为需要修改的代码位于 Consumers -> src -> CustomerDemo -> StoreConsumerObjects.java 第 30->40 行(下面的 try/catch 语句)

写入对象然后读取对象的主要方法

public static void main(String[] args)
{
    try (FileOutputStream fos = new FileOutputStream("customers.dat");
         ObjectOutputStream oos = new ObjectOutputStream(fos)) {

        PreferredCustomer pc = new PreferredCustomer("David Mistretta","943 Fakedale Way, Funnyvale, MO, 01337","978-000-0000","01A001");
        pc.setBalance(550);
        System.out.println("Object to input into customers.dat\n" + pc.toString() +"\n\n");
        oos.writeObject(pc);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try (FileInputStream fis = new FileInputStream("customers.dat");
         ObjectInputStream ois = new ObjectInputStream(fis)) {

        PreferredCustomer pca = (PreferredCustomer) ois.readObject();
        System.out.println("Object output from customers.dat\n" + pca.toString());
        ois.close();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } 
} 

我在 Person.java 中编写的无参数构造函数(第 28 -> 34 行)

public Person() 
{
    System.out.println("Person no arg construct");
    m_name = "";
    m_phoneNumber = "";
    m_address = "";
}

电流输出

Object to input into customers.dat
Preferred Customer
Name: David Mistretta
Address: 943 Fakedale Way, Funnyvale, MO, 01337
Phone Number: 978-000-0000
Customer Number: 01A001
Mailing List: true
Balance: 550.0
Discount: 0.05


Person no arg construct
Object output from customers.dat
Preferred Customer
Name: 
Address: 
Phone Number: 
Customer Number: 01A001
Mailing List: true
Balance: 550.0
Discount: 0.05

我希望名称、地址和电话号码字段在输入时反映这些字段。我遵循了有关如何在此处将对象存储在文件中的说明https://kodejava.org/how-do-i-store-objects-in-file/

如果有人能指出我如何处理这个问题的正确方向,我将不胜感激。

标签: javainheritanceserializableobjectinputstream

解决方案


Serializable必须调用每个非类构造函数。Java 语言禁止其他任何事情。Java 序列化机制必须进行狡猾的字节码验证以避免构造函数。在某些类中,构造函数可能会执行某种安全检查。

但是,超类构造函数在Serializable类上的任何内容之前被调用。所以你的问题可能在其他地方。

(注意:为了改变他们的偏好而破坏和重建人是不受欢迎的。)


推荐阅读