1 @Test2 Public voidTestserializable ()throwsIOException, ClassNotFoundException {3Son son =NewSon ();4 Son.changefieldvalue ();5Bytearrayoutputstream Bytearrayoutputstream =NewBytearrayoutputstream ();6ObjectOutputStream ObjectOutputStream =NewObjectOutputStream (bytearrayoutputstream);7 Objectoutputstream.writeobject (son);8Son.staticfield = 3;9ObjectInputStream ObjectInputStream =NewObjectInputStream (NewBytearrayinputstream (Bytearrayoutputstream.tobytearray ()));Tenson =(Son) objectinputstream.readobject (); One /** A * Output: - * Parent - * Son the * Parent - * son{staticfield=3, s=2, Transientfield=0, p=1} - */ - System.out.println (son); + } - Private Static classSonextendsParentImplementsserializable{ + //Normal serialization A Private ints = 1; at //class fields do not participate in serialization - Private Static intStaticfield = 1; - //transient field does not participate in serialization - Private transient intTransientfield = 1; - //because subclasses implement serializable, the subclass fields are serialized and are not initialized with the declared constructor when deserializing . - //instead of instantiating an empty object directly with the JVM reflection attribute and assigning it, the constructor for the subclass can have no public, no argument constructors. in PrivateSon () { -System.out.println ("Son"); to } + Private voidChangefieldvalue () { - This. S = 2; theSon.staticfield = 2; * This. Transientfield = 2; $ This. P = 2;Panax Notoginseng } - the @Override + PublicString toString () { A return"Son{" + the"staticfield=" + Staticfield + +", s=" + S + -", transientfield=" + Transientfield + $", p=" + p + $‘}‘; - } - } the Private Static classparent{ - //classes that do not implement serializable, fields do not participate in serializationWuyi protected intp = 1; the //because the parent does not implement serializable, the fields Here are not serialized, - //When deserializing a subclass, because the parent class is not serialized, it is necessary to call the constructor of the parent class to initialize the parent class. Wu //the parent class must have a public, non-parametric constructor. - PublicParent () { AboutSystem.out.println ("Parent"); $ } -}
Java Foundation-serializable