代码之家  ›  专栏  ›  技术社区  ›  user3639557

加载序列化对象

  •  0
  • user3639557  · 技术社区  · 6 年前

    Person )在另一个班级里工作:

    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 (...) { ... }
         }
     }
    

    但是,为了保持整洁,有没有可能将它作为函数移到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 回复  |  直到 6 年前
        1
  •  3
  •   Dici gla3dr    6 年前

    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);
        }
    }
    

    附言:我还加了一句 而不是显式的 close()