serialversionuid is static and final but then why is it serializable

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


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());
        }
    }
}

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.

链接地址: http://www.djcxy.com/p/23866.html

上一篇: 为什么用户定义的serialVersionUID在去电时不使用?

下一篇: serialversionuid是静态的和最终的,但为什么它是可序列化的