为了账号安全,请及时绑定邮箱和手机立即绑定

加载序列化对象

加载序列化对象

繁花如伊 2021-09-12 10:28:24
我开始使用java,并开始玩序列化。我想知道是否有任何方法可以在类本身内部编写反序列化函数。让我澄清一下我的意思:我可以Person从另一个类中反序列化一个对象(即来自 class )并且它可以工作:public class Dummy{    ...    public static void main(String args[])    {        ...        Person father = null;        try {            FileInputStream load = new FileInputStream(saved_file);            ObjectInputStream in = new ObjectInputStream(load);            indiv = (Person) in.readObject();            in.close();            load.close();        } catch (...) { ... }     } }但是,为了整洁,是否可以将 this 作为函数移动到 Person 类中?例如,要执行以下操作:public class Person implements Serializable {    private boolean isOrphan = false;    private Person parent;    ...    public void load(File saved_file) {        try {            FileInputStream load = new FileInputStream(saved_file);            ObjectInputStream in = new ObjectInputStream(load);            this = (Person) in.readObject(); // Error: cannot assign a value to final variabl this            in.close();            load.close();         } catch (...) { ... }     }}然后在另一个班级中只需调用:public class Dummy{    ...    public static void main(String args[])    {        ...        Person father = null;        father.load(saved_file);    }}
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

您不能在尚不存在的实例上调用实例方法。即使您的代码可以编译,您也会得到 ,NullPointerException因为您正在调用 上的方法null。


使您的方法静态并使其返回反序列化的实例。更一般地说,this不是可以分配的变量,它是对对象的不可变引用。


public static Person load(File saved_file) {

    try (FileInputStream load = new FileInputStream(saved_file);

         ObjectInputStream in = new ObjectInputStream(load)) {

        return (Person) in.readObject();

     } catch (...) { ... }

 }


public class Dummy {

    public static void main(String args[]) {

        Person father = Person.load(saved_file);

    }

}

PS:我还添加了try-catch 资源而不是显式,close()因为它更安全。


查看完整回答
反对 回复 2021-09-12
  • 1 回答
  • 0 关注
  • 123 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信