关于父类没有无参构造函数的反序列化问题
有没有发现一个问题,如果我们定义三个类Bar Bar1 Bar2,其中Bar2实现了serializable接口,Bar1没有无参构造函数,那么在对Bar2进行反序列化的时候会抛出异常,请问这种情况应该怎么解决呀
有没有发现一个问题,如果我们定义三个类Bar Bar1 Bar2,其中Bar2实现了serializable接口,Bar1没有无参构造函数,那么在对Bar2进行反序列化的时候会抛出异常,请问这种情况应该怎么解决呀
2018-02-24
我这里用你的没有一点问题诶 是不是main函数有问题
你把序列、反序列封装成函数,那我的main函数是这样的:
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("demo/obj2.dat")
);
Bar2 bar2 = new Bar2();
oos.writeObject(bar2);
oos.flush();
oos.close();
// ObjectInputStream ois = new ObjectInputStream(
// new FileInputStream("demo/obj2.dat")
// );
// Bar2 bar2 = (Bar2)ois.readObject();
// System.out.println(bar2);
// ois.close();
class Bar { Bar() { a = 1; System.out.println("Bar..." + a); } protected int a; } class Bar1 extends Bar implements Serializable { Bar1(double b) { this.b = b; System.out.println("Bar1..." + b); } Bar1() { this.b = 1.5; System.out.println("Bar1..." + b); } protected double b; } class Bar2 extends Bar1 { /** * */ private static final long serialVersionUID = 270589360374420361L; Bar2() { super(); c = 3; System.out.println("Bar2..." + c); } protected int c; } 代码是这样的,主函数里面是: String file = "C:\\JAVA\\1.txt"; Bar2 bar2 = new Bar2(); // objectSerialize(bar2, file); objectDeserialize(bar2, file); System.out.println(bar2); 抛出了一坨异常: Exception in thread "main" java.io.InvalidClassException: com.clcl.io.Bar1; local class incompatible: stream classdesc serialVersionUID = 7973625721886668699, local class serialVersionUID = -1556330232670652696 at java.base/java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:689) at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1894) at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1763) at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1894) at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1763) at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2051) at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1585) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:422) at com.clcl.io.FileTest.objectDeserialize(FileTest.java:83) at com.clcl.io.FileTest.main(FileTest.java:44)
举报