gpt4 book ai didi

java - writeObject() 如何访问 serialPersistantFields

转载 作者:行者123 更新时间:2023-11-29 04:29:50 24 4
gpt4 key购买 nike

需要序列化,我理解这一点,但是 stream.defaultWriteObject() 如何实际访问它们,因为它们是私有(private)的、静态的和最终的。

我的 CS 讲师无法解释这一点(或者他只是不想解释),而且(据我所知)也没有任何文档可以解释这种机制。

即使是抽象的解释也是非常受欢迎的!

最佳答案

我们通常采用的获取私有(private)字段的方式:反射。具体通过Field.setAccessible(true)。这是他们执行此操作的代码,来自 java.io.ObjectStreamClass,Java 8:

/**
* Returns serializable fields of given class as defined explicitly by a
* "serialPersistentFields" field, or null if no appropriate
* "serialPersistentFields" field is defined. Serializable fields backed
* by an actual field of the class are represented by ObjectStreamFields
* with corresponding non-null Field objects. For compatibility with past
* releases, a "serialPersistentFields" field with a null value is
* considered equivalent to not declaring "serialPersistentFields". Throws
* InvalidClassException if the declared serializable fields are
* invalid--e.g., if multiple fields share the same name.
*/
private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl)
throws InvalidClassException
{
ObjectStreamField[] serialPersistentFields = null;
try {
Field f = cl.getDeclaredField("serialPersistentFields");
int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
f.setAccessible(true);
serialPersistentFields = (ObjectStreamField[]) f.get(null);
}
} catch (Exception ex) {
}

关于java - writeObject() 如何访问 serialPersistantFields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com