Java serialization (2)-writeObject/readObject, javawriteobject

Source: Internet
Author: User

Java serialization (2)-writeObject/readObject, javawriteobject

The previous article "Java Serialization" gave us a general introduction to Serialization and deserialization, as well as parsing serialized files. Next, let's take a look at how JDK serializes an Object.

In the serialization process, the virtual opportunity attempts to call the writeObject () and readObject () in the object class for custom serialization and deserialization. If not, the ObjectOutputStream is called. defaultWriteObject () and ObjectInputStream. defaultReadObject (). Likewise, the most important methods in ObjectOutputStream and ObjectInputStream are writeObject () and readObject (), recursively writing/reading bytes.

Therefore, you can customize the serialization and deserialization logic through writeObject () and readObject. The logic for encrypting sensitive information can also be stored here. [But serialVersionUID will not be checked here]

For an Obj, the class information description is first written, and then the attribute field is written.

The following are defaultWriteObject () and defaultReadObject (). For details, see ObjectOutputStream and ObjectInputStream of JDK1.8.

    public void defaultWriteObject() throws IOException {        SerialCallbackContext ctx = curContext;        if (ctx == null) {            throw new NotActiveException("not in call to writeObject");        }        Object curObj = ctx.getObj();        ObjectStreamClass curDesc = ctx.getDesc();        bout.setBlockDataMode(false);        defaultWriteFields(curObj, curDesc);        bout.setBlockDataMode(true);    }    private void defaultWriteFields(Object obj, ObjectStreamClass desc) {        Class<?> cl = desc.forClass();        if (cl != null && obj != null && !cl.isInstance(obj))             throw new ClassCastException();        desc.checkDefaultSerialize();        int primDataSize = desc.getPrimDataSize();        if (primVals == null || primVals.length < primDataSize)             primVals = new byte[primDataSize];        desc.getPrimFieldValues(obj, primVals);        bout.write(primVals, 0, primDataSize, false);        ObjectStreamField[] fields = desc.getFields(false);        Object[] objVals = new Object[desc.getNumObjFields()];        int numPrimFields = fields.length - objVals.length;        desc.getObjFieldValues(obj, objVals);        for (int i = 0; i < objVals.length; i++) {            if (extendedDebugInfo)                 debugInfoStack.push(                    "field (class \"" + desc.getName() + "\", name: \"" +                    fields[numPrimFields + i].getName() + "\", type: \"" +                    fields[numPrimFields + i].getType() + "\")");            writeObject0(objVals[i], fields[numPrimFields + i].isUnshared());    }
From the code above, we can see that JAVA divides the data into basic types and Objects Based on the field type during the write serialization process.

Parse basic type getPrimFieldValues ()

JAVA records the corresponding memory address of the field in the object, assembles It In The FieldReflector object, and then reads the value of the basic type through unsafe, and convert it into the final byte [] to be written.

[The above operations are completed in ObjectStreamClass]

        fieldRefl = getReflector(fields, this);FieldReflector(ObjectStreamField[] fields) {            this.fields = fields;            int nfields = fields.length;            readKeys = new long[nfields];            writeKeys = new long[nfields];            offsets = new int[nfields];            typeCodes = new char[nfields];            ArrayList<Class<?>> typeList = new ArrayList<>();            Set<Long> usedKeys = new HashSet<>();            for (int i = 0; i < nfields; i++) {                ObjectStreamField f = fields[i];                Field rf = f.getField();                long key = (rf != null) ?                    unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;                readKeys[i] = key;                writeKeys[i] = usedKeys.add(key) ? key : Unsafe.INVALID_FIELD_OFFSET;                offsets[i] = f.getOffset();                typeCodes[i] = f.getTypeCode();                if (!f.isPrimitive())                     typeList.add((rf != null) ? rf.getType() : null);            }            types = typeList.toArray(new Class<?>[typeList.size()]);            numPrimFields = nfields - types.length;        }void getPrimFieldValues(Object obj, byte[] buf) {            if (obj == null) throw new NullPointerException();            for (int i = 0; i < numPrimFields; i++) {                long key = readKeys[i];                int off = offsets[i];                switch (typeCodes[i]) {                    case 'Z':                        Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));                        break;                    case 'B':                        buf[off] = unsafe.getByte(obj, key);                        break;                    case 'C':                        Bits.putChar(buf, off, unsafe.getChar(obj, key));                        break;                    case 'S':                        Bits.putShort(buf, off, unsafe.getShort(obj, key));                        break;                    case 'I':                        Bits.putInt(buf, off, unsafe.getInt(obj, key));                        break;                    case 'F':                        Bits.putFloat(buf, off, unsafe.getFloat(obj, key));                        break;                    case 'J':                        Bits.putLong(buf, off, unsafe.getLong(obj, key));                        break;                    case 'D':                        Bits.putDouble(buf, off, unsafe.getDouble(obj, key));                        break;                    default: throw new InternalError();                }            }        }

【The conversion between basic types and byte is handled in the Bits class. If you are interested in it, you can take a good look at the conversion of Basic Types and byte in JAVA.]

In addition, float and double are converted to long and byte first.

Public static native intFloatToRawIntBits (FloatValue );

Public static native longDoubleToRawLongBits (DoubleValue );


Parse object type getObjFieldValues ()

Writing objects is more complex than basic types. JDK first needs to check whether the Class has serialized records and can reuse ClassDesc directly. In addition, it needs to determine the object type,Null,Handle,Class,Array,String,Enum. At last, writeSerialData () and defaultWriteFields () will be called in writeOrdinaryObject () to recursively write the basic type.

For more information, see ObjectOutputStream. writeObject0.
    private void writeObject0(Object obj, boolean unshared) {        boolean oldMode = bout.setBlockDataMode(false);        depth++;        try {            // check for replacement object            Object orig = obj;            Class<?> cl = obj.getClass();            ObjectStreamClass desc;            for (;;) {                Class<?> repCl;                desc = ObjectStreamClass.lookup(cl, true);                if (!desc.hasWriteReplaceMethod() ||                    (obj = desc.invokeWriteReplace(obj)) == null ||                    (repCl = obj.getClass()) == cl) break;                cl = repCl;            }            if (enableReplace) {                Object rep = replaceObject(obj);                if (rep != obj && rep != null) {                    cl = rep.getClass();                    desc = ObjectStreamClass.lookup(cl, true);                }                obj = rep;            }            // if object replaced, run through original checks a second time            if (obj != orig) {                subs.assign(orig, obj);                if (obj == null) {                    writeNull();                    return;                } else if (!unshared && (h = handles.lookup(obj)) != -1) {                    writeHandle(h);                    return;                } else if (obj instanceof Class) {                    writeClass((Class) obj, unshared);                    return;                } else if (obj instanceof ObjectStreamClass) {                    writeClassDesc((ObjectStreamClass) obj, unshared);                    return;                }            }            // remaining cases            if (obj instanceof String) {                writeString((String) obj, unshared);            } else if (cl.isArray()) {                writeArray(obj, desc, unshared);            } else if (obj instanceof Enum) {                writeEnum((Enum<?>) obj, desc, unshared);            } else if (obj instanceof Serializable) {                writeOrdinaryObject(obj, desc, unshared);            } else                 throw new NotSerializableException(cl.getName());        } finally {            depth--;            bout.setBlockDataMode(oldMode);        }    }


In addition, I have read the typical String serialization policy. The first character is the String type identifier, which includes a common String and a long String, followed by the length, and finally the content is written in UTF.

    private void writeString(String str, boolean unshared) throws IOException {        handles.assign(unshared ? null : str);        long utflen = bout.getUTFLength(str);        if (utflen <= 0xFFFF) {            bout.writeByte(TC_STRING);            bout.writeUTF(str, utflen);        } else {            bout.writeByte(TC_LONGSTRING);            bout.writeLongUTF(str, utflen);        }    }    void writeUTF(String s, long utflen) throws IOException {        if (utflen > 0xFFFFL)             throw new UTFDataFormatException();        writeShort((int) utflen);        writeBytes(s);    }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.