我有一个包含大量信息的类Bucket
,我只想将其中的两个字段存储(可序列化)到一个文件中。因此,我使 Bucket
扩展了 ChatData
,它只保存这两个字段,因为我认为在向上转换时,我可能会丢失无用的信息并存储 bucket
对象作为 chatdata
对象。
但是,向上转换为父类(super class)并不会使对象丢失其子类信息。我怎样才能实现这个目标?
public class ChatData implements Serializable {
private int f1 = 1;
private int f2 = 2;
}
public class Bucket extends ChatData implements Serializable {
private int f3 = 3;
private int f4 = 4; // useless data when it comes to storing
private int f5 = 5;
public void store(ObjectOutputStream oos) {
oos.writeObject( (ChatData) this ); // does also store f3, f4, f5,
// ... but I don't whant these!
// also, unnecessary cast, does not do anything
}
public static void main(String[] args) {
Bucket b = new Bucket();
b.store(new ObjectOutputStream(new FileOutputStream("C:/output.dat"));
}
}
(未经测试的代码,仅用于可视化)
如何将我的 Bucket
对象作为 ChatData
对象写入我的硬盘?如果没有,仅部分存储对象的首选方式是什么?
我可以想到一个简单的解决方案,例如创建一个全新的 ChatData
对象,但我宁愿了解最好的方法是什么。
最佳答案
如果您不想序列化类的成员。只需将其标记为 transient
即可。
在您的特定情况下,您不需要经历创建父类(super class)的麻烦。改为执行此操作:
public class Bucket implements Serializable {
transient private int f3 = 3;
transient private int f4 = 4; // useless data when it comes to storing
transient private int f5 = 5;
private int f1 = 1;
private int f2 = 2;
//leave the remaining code in this class as it is
}
关于java - 转换为父类并丢失信息 - 存储对象的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417160/