我开始使用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);
}
}
慕尼黑5688855
相关分类