Serialize a java.awt.geom.Area

后端 未结 4 1263
时光说笑
时光说笑 2021-01-20 02:47

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 converti

4条回答
  •  感情败类
    2021-01-20 03:35

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

提交回复
热议问题