Serialize java.awt.geom.Area

I need to serialize an Area object (java.awt.geom.Area) on a socket. However, this is not like serializability. Is there any way to do this? Maybe by converting it to another object?

Thanks in advance

+3
source share
3 answers

I found this workaround:

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

The result is a form that can be serialized.

+6
source

Use XStream to convert it to / from XML. You do not need your object to implement certain interfaces, and serialization is customizable.

+1
source

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

Source: https://habr.com/ru/post/1741247/


All Articles