Serialize a java.awt.geom.Area

半世苍凉 提交于 2019-12-04 04:20:15

问题


I have the need to serialize an Area object (java.awt.geom.Area) in a socket. However it doesn't seem to be serializable. Is there a way to do such thing? Maybe by converting it into a different object?

Thanks in advance


回答1:


I found this workaround:

AffineTransform.getTranslateInstance(0,0).createTransformedShape(myArea)

This results in a shape that can be serialized.




回答2:


Use XStream to trivially convert it to/from XML. You don't need your object to implement particular interfaces, and the serialisation is customisable.




回答3:


From kieste's answer, this work-around can be derived.

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()));
    }
}


来源:https://stackoverflow.com/questions/2644172/serialize-a-java-awt-geom-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!