最近在一次采访中有人问我一个问题:
There are 100 properties in a Java class and I should be able to serialize only 2 of the properties. How is this possible?
标记所有 98 个属性并不是解决问题的方法,因为它效率不高。 我的答案是将这些属性分割成一个单独的类并使其可序列化。
但是有人告诉我,不允许我修改类的结构。 好吧,我试图在在线论坛中找到答案,但没有成功。
最佳答案
如果是关于几个字段,那么您总是可以将它们标记为transient
。但是,如果您在序列化中需要更多可控逻辑,那么 Externalizable
是答案。您可以通过实现 Externalizable
接口(interface)的方法 writeExternal
和 readExternal
方法来覆盖序列化和反序列化过程。
这是一个小代码,展示了如何只序列化几个字段
public class Person implements Externalizable {
String name;
int age;
public Person() { }
Person(String name, int age) {
this.name = name;
this.age = age;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
//out.writeInt(age); // don't write age
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject(); // read only name and not age
}
}
关于java - 如何仅序列化 Java 类中的极少数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30953874/