A preliminary study of Java Serialization (2)-writeobject/readobject

Source: Internet
Author: User

The previous article, " Exploring Java Serialization (serialization)", gives us a general description of what serialization and deserialization is, and parses the serialized file. Then let's look at how the JDK serializes an object.

During serialization, the virtual opportunity attempts to invoke the writeobject() and ReadObject() in the object class for user-defined serialization and deserialization, and if none is called Objectoutputstream.defaultwriteobject() and objectinputstream.defaultreadobject(). Similarly, the most important methods in ObjectOutputStream and ObjectInputStream are WriteObject () and ReadObject (), which write/read recursively into byte.

So users can customize the serialization and deserialization logic through WriteObject () and ReadObject (). The logic of encrypting some sensitive information can also be placed here. "But we won't check serialversionuid here."

For an obj, write the class information descriptionFirst, then write the attribute field.

Below are Defaultwriteobject () and Defaultreadobject (), see JDK1.8 ObjectOutputStream and ObjectInputStream.

    public void Defaultwriteobject () throws IOException {Serialcallbackcontext ctx = Curcontext;        if (CTX = = null) {throw new Notactiveexception ("Not on 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 ()); }
As can be seen from the code above, Java, in the process of serializing write, is divided by the type of fieldBasic TypeAndObject。

Parsing basic Typesgetprimfieldvalues()

JAVA will put the object Field the corresponding memory address is recorded and assembled in Fieldreflector object, and then through the unsafe to read the value of the underlying type and convert it to the final byte [].

"The above operations are done 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 (ob                        J, 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 (); }            }        }

" basic types and byte conversions are handled in the Bits class, and if you're interested, you can look at Basic Types in JAVA and conversion of byte "

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

Public Static native int Floattorawintbits (floatvalue);

Public Static native Long Doubletorawlongbits (doublevalue);


Resolving Object Typesgetobjfieldvalues()

Writing objects is more complex than the basic type, the JDK first to see whether Class is already serialized records, you can directly reuse Classdesc, also need to determine the type of object,Null,Handle,Class ,Array,String,Enum , and so on. Finally, Writeserialdata () and Defaultwritefields () are called in writeordinaryobject() to recursively write the base type.

For details, refer to Objectoutputstream.writeobject0 () below.
    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 secondTime 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) o            BJ, 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); }    }


Besides, I looked at it.A typical string serialization strategy。 The first character is identified as a type of string, has an ordinary string and a long string, then marks the length, and finally the content is written with 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 utfdataformatexcept Ion ();        Writeshort ((int) utflen);        Writebytes (s);    }
   


Preliminary discussion of Java Serialization (2)-writeobject/readobject

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.