简体   繁体   中英

Read/Write Arraylist<java.awt.geom.Area> through socket

How can i send an Arraylist<java.awt.geom.Area> through socket ? because Area is not Serializable it gives a NotSerializableException is there any way to send it ?

In order to send a non-Serializable class over a network connection you must provide code to "serialize" it yourself. This means setting up a serialization encoding/format ie convert it to a String or binary representation, writing code to produce this format, and also code that can parse the String/binary representation and recreate an instance of the object.

This means that you must have access to (and encode in your String/binary representation), sufficient internal state to be able to recreate an equivalent object when you deserialize it. Since java.awt.geom.Area doesn't natively support serialization, it's all up to you.

For a simple class it could be sufficient to call toString() to serialize and write some simple code to parse that output string to rebuild an equivalent object. How to do this for a complex class would depend on the internals of the class and is probably beyond what can be explained on SO.

For Area this is probably non-trivial since there are so many different Shape classes it can represent.

Path2D.Float and Path2D.Double are serializable, so you can send one of those instead.

Sending side:

void writeAreas(List<Area> areas, ObjectOutputStream stream)
throws IOException {
    List<Path2D> paths = new ArrayList<>(areas.size());
    for (Area area : areas) {
        paths.add(new Path2D.Float(area));
    }
    stream.writeObject(paths);
}

Receiving side:

List<Area> readAreas(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
    List<?> paths = (List<?>) stream.readObject();
    List<Area> areas = new ArrayList<>(paths.size());
    for (Object pathObj : paths) {
        Shape path = (Shape) pathObj;
        areas.add(new Area(path));
    }
    return areas;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM