Java有一个transient关键字,它与默认序列化一起使用来指示不应序列化的值。但是,如果我将 XML 序列化与 XMLDecoder 结合使用,则与该字段关联的属性仍会被序列化。我在 JSON 中使用 Gson 库进行了相同的尝试,并且 transient 字段似乎确实被正确跳过。
有什么想法吗?
最佳答案
XML 编码器/解码器青睐 @XMLTransient
注释。
transient
关键字用于 Java 对象序列化过程,最终以字节序列结束。 XML“序列化”最终形成格式化的文本文档。当您选择不序列化的字段(通过将其标记为 transient )时,可能会有不同的方面,并且由于输出完全不同,您可能想要选择要排除的不同字段并自行处理它们。例如,在 Java 序列化的情况下,您可能希望选择序列化 byte[]
,因为它既简单又直接。对于 XML,您可能希望序列化用于创建该字节数组的对象(如果它具有更好/更有意义的文本表示形式)。
@XMLTransient
由 JAXB
使用。要使 XMLEncoder
排除某个字段(将其标记为 transient ),您必须在其 PropertyDescriptor 中将
: ( source )"transient"
属性设置为 TRUE
BeanInfo info = Introspector.getBeanInfo(JTextField.class);
PropertyDescriptor[] propertyDescriptors =
info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("text")) {
pd.setValue("transient", Boolean.TRUE);
}
}
这不是一个优雅的解决方案。另一种方法是使用 JAXB
而不是 XMLEncoder
。
关于java - 为什么 XMLDecoder 不尊重 transient 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889719/