我需要在套接字中序列化一个Area对象(java.awt.geom.Area)。但它似乎不是可序列化的。有没有办法做这样的事情?也许通过将其转换为不同的对象?
提前致谢
我发现了这个解决方法:
AffineTransform.getTranslateInstance(0,0).createTransformedShape(myArea)
这导致可以序列化的形状。
使用XStream将其简单地转换为XML或从XML转换。您不需要对象来实现特定接口,并且可以自定义序列化。
根据kieste的回答,可以推导出这种解决方法。
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.io.IOException;
import java.io.Serializable;
public class SerialArea extends Area implements Serializable {
private static final long serialVersionUID = -3627137348463415558L;
/**
* New Area
*/
public SerialArea() {}
/**
* New Area From Shape
*/
public SerialArea(Shape s) {
super(s);
}
/**
* Writes object out to out.
* @param out Output
* @throws IOException if I/O errors occur while writing to the
* underlying OutputStream
*/
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
out.writeObject(AffineTransform.getTranslateInstance(0, 0).
createTransformedShape(this));
}
/**
* Reads object in from in.
* @param in Input
* @throws IOException if I/O errors occur while writing to the
* underlying OutputStream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found.
*/
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
add(new Area((Shape) in.readObject()));
}
}