Question

As we know that static fields are not serializable,

but the serialversionUID in our class is final and static, How is it serialized even if it is static and final

Was it helpful?

Solution

During the serialization process, one of the things that gets written is the class descriptor. This class descriptor contains the name and the serialVersionUID of the class.

The method can be found in the class java.io.ObjectStreamClass(http://docs.oracle.com/javase/7/docs/api/java/io/ObjectStreamClass.html)

/**
 * Writes non-proxy class descriptor information to given output stream.
 */
void writeNonProxy(ObjectOutputStream out) throws IOException {
    out.writeUTF(name);
    out.writeLong(getSerialVersionUID());

    byte flags = 0;
    if (externalizable) {
        flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
        int protocol = out.getProtocolVersion();
        if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
            flags |= ObjectStreamConstants.SC_BLOCK_DATA;
        }
    } else if (serializable) {
        flags |= ObjectStreamConstants.SC_SERIALIZABLE;
    }
    if (hasWriteObjectData) {
        flags |= ObjectStreamConstants.SC_WRITE_METHOD;
    }
    if (isEnum) {
        flags |= ObjectStreamConstants.SC_ENUM;
    }
    out.writeByte(flags);

    out.writeShort(fields.length);
    for (int i = 0; i < fields.length; i++) {
        ObjectStreamField f = fields[i];
        out.writeByte(f.getTypeCode());
         out.writeUTF(f.getName());
        if (!f.isPrimitive()) {
            out.writeTypeString(f.getTypeString());
        }
    }
}

OTHER TIPS

It isn't serialised in the way you mean. It is transmitted as part of the class information the first time an instance of the class is serialized. It isn't the same thing.

serialVersionUID is a static field and isn't transmitted with the object. But serialVersionUID is transmitted with the class, and that class is subject to the handle mechanism, which means it is only transmitted once per stream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top