我正在尝试序列化Path2D.Double的子类,序列化有效,但反序列化不会因为以下异常:
Exception in thread "main" java.io.InvalidClassException: CustomShape; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:147)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:755)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at CustomShape.main(CustomShape.java:38)
这可能是由于超类Path2D没有实现Serializable吗?但是,Path2D.Double本身也无法反序列化。
这是我的代码:
import java.awt.geom.Path2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class CustomShape extends Path2D.Double {
private static final long serialVersionUID = 1L;
public CustomShape() {
super();
}
public static void main(String[] args) throws Exception {
//Make Shape
//Path2D shape = new Path2D.Double(); //works
Path2D shape = new CustomShape(); //doesn't work
shape.moveTo(0, 0);
shape.lineTo(0, 10);
shape.lineTo(10, 10);
shape.lineTo(10, 0);
shape.closePath();
File file = new File(System.getProperty("user.dir"), "shape");
//Save Shape
if (!file.exists()) {
file.createNewFile();
}
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(shape);
out.flush();
out.close();
//Load Shape
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
Object obj = in.readObject();
in.close();
System.out.println(obj);
}
}
答案 0 :(得分:4)
上周我遇到了同样的问题,终于在今天找到了答案。 Path2D对象将其构造函数声明为package-private。由于java序列化要求第一个非可序列化的父类具有no-arg构造函数,并且它不可访问,因此不在Path2D自己的包中的Path2D的任何扩展都不会反序列化。老实说,我认为这是Java方面的一个漏洞,因为使用Float / Double子类的所有其他AWT抽象形状都将其默认构造函数声明为受保护。
如果你很好奇,我通过追踪java.io.ObjectStreamClass.getSerializableConstructor(Class<?>)
找到了根本原因。您会发现它在找到无法访问的构造函数时返回null。