Search code examples
javareflectionxstream

Reaching static field declared in serialPersistentFields


So xstream (v1.4.8) with this line

private Object More ...readField(ObjectStreamField field, Class type, Object instance) {
        try {
           Field javaField = type.getDeclaredField(field.getName());

more here
tries to reach the field named "list" (field.getName() returns "list")

private static final ObjectStreamField[] serialPersistentFields = {
             new ObjectStreamField("list", VirtualFilePermission[].class)
     };

declared in org.jboss.vfs.VirtualFilePermissionCollection but runs into NoSuchFieldException. Why is that?


Solution

  • An ObjectStreamField describes a field that is stored in the serialized stream. While the default mechanism will create an ObjectStreamField for each real instance field of a class, the possibility to override it via a static final ObjectStreamField[] serialPersistentFields field exists exactly for the purpose to declare a list of stream fields which do not match the actual instance fields.

    Such fields can’t be processed by the default algorithm of just reading and writing field values via Reflection. Instead, the dedicated writeObject and readObject methods are required which will read and write the stream fields and process their values.

    The problem here is that the class VirtualFilePermissionCollection has such a mismatching field declaration, as the stream field is named list and the actual instance field is named permissions, and an appropriate readObject method (despite its unnecessary use of Reflection to access its field) but lacks a matching writeObject method. Since a dedicated writeObject method is missing, the default algorithm is used and fails because, as said, the fields don’t match.