gpt4 book ai didi

java - java从文件中读取对象

转载 作者:行者123 更新时间:2023-12-01 18:43:52 26 4
gpt4 key购买 nike

执行以下代码后,打印的字符串值为空。为什么? (当然我已经将对象写入文件了)。任何人都可以在这方面帮助我吗?

class Demo {
protected String name;
protected String address;
}

class Demo1 extends Demo implements Serializable
{
transient int age;
Demo1(String name,String address,int age)
{
this.name=name;
this.address=address;
this.age=age;
}
}
public class FileRead
{
public static void main(String args[])
{
Demo1 ob=new Demo1("Rose","Rohini",23);
try
{
FileInputStream fileIn = new FileInputStream("Demo.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
ob = (Demo1) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}
catch(ClassNotFoundException c)
{
System.out.println("Demo class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Details...");
System.out.println("Name: " + ob.name);
System.out.println("Address: " + ob.address);
System.out.println("age " + ob.age);
}
}

最佳答案

父类(super class)Demo不是Serialized。因此,在保存 Demo1 对象时,不可能保存父类(super class)型的 public、protected 和(如果可访问)包字段。

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state.

代码已更新 -

class Demo implements Serializable  {
protected String name;
protected String address;
}

在这种情况下,你就出去 -

Rose - Rohini - 0

由于年龄是暂时的,因此不会被存储。

关于java - java从文件中读取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18734693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com