对Externalizable对象反序列化时,会先调用类的不带参数的构造方法,这是有别于默认反序列方式的。如果把类的不带参数的构造方法删除,或者把该构造方法的访问权限设置为private、默认或protected级别,会抛出java.io.InvalidException: no valid constructor异常,因此Externalizable对象必须有默认构造函数,而且必需是public的。
staticclassEmployeeimplementsSerializable {String name;int age;staticString local ="earth";transientint ssh;String test;publicvoidtest() {System.out.println("this is test method!"); }}
这时候运行的时候会报错:
java.io.InvalidClassException: com.wangjun.othersOfJava.SerializeDemo$Employee; local class incompatible: stream classdesc serialVersionUID = 4506166831890198488, local class serialVersionUID = 785960679919880606
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at com.wangjun.othersOfJava.SerializeDemo.main(SerializeDemo.java:32)
staticclassEmployeeimplementsSerializable {privatestaticfinallong serialVersionUID =1L;String name;int age;staticString local ="earth";transientint ssh;publicvoidtest() {System.out.println("this is test method!"); }}
将刚才注释的代码取消注释,运行一遍再注释掉,并且新增字段test:
staticclassEmployeeimplementsSerializable {privatestaticfinallong serialVersionUID =1L;String name;int age;staticString local ="earth";transientint ssh;String test;publicvoidtest() {System.out.println("this is test method!"); }}