我喜欢序列化一个列表,当它保存时,它确实包含列表中某个元素是Child 的信息,但是当我尝试读取它时,它返回一个未初始化的信息父类
public static List<Parent> myList = new ArrayList<Parent>();
ds = new Child(3, 4, 3, "zh", "hj" , "ni", p);
myList.add(ds);
try {
logToFile(myList, saveTo); //My method for saving
} catch (URISyntaxException e) {
e.printStackTrace();
}
myList = (List<Parent>) readFromFile(saveTo); //My method for reading
//My list containing null for each Child
我可能还应该包括Parent是抽象类并扩展第三方类
修改 这是我的保存和阅读功能
public void logToFile(Object o, File f) throws URISyntaxException
{
try
{
FileOutputStream fout = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(o);
oos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
public Object readFromFile(File f) throws ClassNotFoundException, IOException {
FileInputStream is = new FileInputStream(f);
ObjectInputStream g = new ObjectInputStream(is);
Object oggg = g.readObject();
g.close();
return oggg;
}
家长和孩子的班级
public class Child extends Parent implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = -8270915411149374357L;
public Child(int x, int z, int y, Material m, String Title) {
super(m, Title);
this.x = x;
this.y = y;
this.z = z;
}
public abstract class Parent extends ItemStack implements java.io.Serializable{
// ItemStack是第三方类
/**
*
*/
private static final long serialVersionUID = -904093000933705904L;
public Parent(Material M, String name) {
super(M);
setName(name);
}
程序生成的文本文件的短片段: