我正在开始java,并开始玩序列化。我想知道是否有任何方法可以在类本身内部编写反序列化函数。让我澄清一下我的意思:我可以从另一个类中反序列化一个对象(即来自类 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);
}
}
最佳答案
您无法在尚不存在的实例上调用实例方法。即使您的代码可以编译,您也会收到 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()
,因为它更安全。
关于java - 加载序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52248195/