java - 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/
如果有人能指出我如何处理这个问题的正确方向,我将不胜感激。
解决方案
Serializable
必须调用每个非类构造函数。Java 语言禁止其他任何事情。Java 序列化机制必须进行狡猾的字节码验证以避免构造函数。在某些类中,构造函数可能会执行某种安全检查。
但是,超类构造函数在Serializable
类上的任何内容之前被调用。所以你的问题可能在其他地方。
(注意:为了改变他们的偏好而破坏和重建人是不受欢迎的。)
推荐阅读
- laravel - Laravel - 作曲家更新:连接被拒绝
- javascript - 如何检测浏览器的哪一侧是滚动条 - 向右或向左(在 RTL 的情况下)?
- c++ - 如何在 C++ 中正确重载运算符 cast char*?
- javascript - 使用数据库中的 Google Charts 创建堆积图
- javascript - 匹配正则表达式模式仅计算单词列表中的唯一值
- php - 一个特定的 Wordpress 页面上的 PHP
- php - 如何在邮递员中测试laravel模型关系
- jsp - Struts 应用程序与 Vue.js Webpack 捆绑在一起
- c# - C# 应用程序如何知道系统日期时间格式已更改?
- login - 在 Outlook 365 中使用对话框 API 打开模式会显示“新窗口”警报