我有一个包含大量信息的类Bucket,我只想将其中的两个字段存储到一个文件中。因此,我让Bucket扩展ChatData只保存这两个字段,因为我认为在向上转换时,可能会丢失无用的信息,然后将bucket对象存储为chatdata对象。
但是,相反,向上转换到超类并不会使对象失去其子类信息。我怎样才能做到这一点?
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对象,但我更愿意了解什么是最好的方法。
发布于 2015-04-02 15:52:52
如果您不想序列化类的一个成员。把它标记为transient。
在您的特殊情况下,您不需要经历创建超类的麻烦。取而代之的是这样做:
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
}https://stackoverflow.com/questions/29417160
复制相似问题