繁体   English   中英

如何仅序列化Java类中的极少数属性

[英]How to serialize only a very few properties in a Java class

最近在一次采访中我被问到一个问题:

Java类中有100个属性,我应该只能序列化其中的2个属性。 这怎么可能?

标记所有98个属性不是答案,因为它效率不高。 我的答案是将这些属性划分为一个单独的类并使其可序列化。

但我被告知,我不会被允许修改班级的结构。 好吧,我试图在网上论坛找到答案,但是徒劳无功。

如果它只是几个字段,那么你总是可以将它们标记为transient 但是如果你的搜索需要更多的控制逻辑,那么Externalizable就是答案。 您可以通过实现Externalizable接口的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的transient关键字。 如果你创建一个类的瞬态属性,它将不会被序列化或反序列化。 例如:

private transient String nonSerializeName;

您可以在使用Externalizable接口的情况下覆盖序列化行为,

你需要添加以下方法并在那里做必要的,

private void writeObject(ObjectOutputStream out) throws IOException;

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

例如,类可能看起来像这样,

class Foo{
  private int property1;
  private int property2;
  ....
  private int property100;

  private void writeObject(ObjectOutputStream out) throws IOException
  {
     out.writeInt(property67);
     out.writeInt(property76);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
  {
    property67 = in.readInt();
    property76 = in.readInt();
  }
}

请参阅了解更多详情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM