The control serialization field can also use the Externalizable interface to replace serializable excuses. you need to define a default constructor at this point, otherwise you will get an exception (Java.io.InvalidClassException:Person; person; No
Valid constructor); You also need to define two methods (Writeexternal () and readexternal ()) to control which fields are to be serialized.
In the Person class
Packagecom.kc.iotest02;Importjava.io.Externalizable;Importjava.io.IOException;ImportJava.io.ObjectInput;ImportJava.io.ObjectOutput; Public classPersonImplementsexternalizable {PrivateString name; Private intAge ; /*** must have parameter-free constructors*/ PublicPerson () {System.out.println ("Parameterless constructor"); } PublicPerson (String name,intAge ) {System.out.println ("Constructor with parameters"); This. name=name; This. age=Age ; } @Override PublicString toString () {//TODO auto-generated Method Stub return"The name is" +name+ "age is" +Age ; } @Override Public voidWriteexternal (ObjectOutput out)throwsIOException {//TODO auto-generated Method Stubout.writeobject (name); Out.writeobject (age); } @Override Public voidReadexternal (ObjectInput in)throwsIOException, ClassNotFoundException {//TODO auto-generated Method Stub This. name=(String) in.readobject (); This. age= (int) In.readobject (); }}
To test the code in a class
Public Static voidMain (string[] args)throwsIOException {//TODO auto-generated Method StubFileOutputStream Fos=NULL; ObjectOutputStream Oos=NULL; FileInputStream FIS=NULL; ObjectInputStream Ois=NULL; Try{fos=NewFileOutputStream (NewFile ("E://javanewlskd.txt")); Oos=NewObjectOutputStream (FOS); Oos.writeobject (NewPerson ("Monkey King", 600)); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { if(oos!=NULL) {oos.close (); } } Try{FIS=NewFileInputStream (NewFile ("E://javanewlskd.txt")); Ois=NewObjectInputStream (FIS); Person per=(person) ois.readobject (); System.out.println (per); } Catch(Exception e) {e.printstacktrace (); } finally { if(ois!=NULL) {ois.close (); } } }
Externalizable Interface for Java serialization