且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时从类序列化中排除字段?

更新时间:2023-01-15 23:10:30

ObjectOutputStream文档说:


默认值对象的序列化机制会写入对象的类,类签名以及所有非瞬态和非静态字段的值。对其他对象的引用(瞬态或静态字段除外)也会导致写入这些对象。

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also.

因此,当您将变量声明为瞬态,ObjectOutputStream应该忽略它。确保使用 transient 关键字而不是 @Transient 注释。某些ORM框架使用此类注释来标记不应保存在数据库中的字段。它们对于buildin序列化框架毫无意义。

So when you declare a variable as transient, it should be ignored by ObjectOutputStream. Make sure that you use the transient keyword and not a @Transient annotation. Such annotations are used by some ORM frameworks to mark fields which are not supposed to be saved in databases. They are meaningless for the buildin serialization framework.

private transient String foo; // Field gets ignored by ObjectOutputStream
@Transient private String bar; // Treated normally by ObjectOutputStream (might mean something for some other framework)