[英]Loading serialized object
我開始使用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()
因為它更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.