如何序列化第三方非序列化的最终类(例如谷歌的LatLng类)?

时间:2013-01-08 17:19:44

标签: java serialization

我正在使用v2 Google Play服务中的Google's LatLng class。该特定类是最终的,不实现java.io.Serializable。有什么方法可以让LatLng类实现Serializable吗?

public class MyDummyClass implements java.io.Serializable {
    private com.google.android.gms.maps.model.LatLng mLocation;

    // ...
}

我不想声明mLocation 瞬态

2 个答案:

答案 0 :(得分:29)

它不是Serializable,而是Parcelable,如果这是一个选项。如果没有,你可以自己处理序列化:

public class MyDummyClass implements java.io.Serialiazable {
    // mark it transient so defaultReadObject()/defaultWriteObject() ignore it
    private transient com.google.android.gms.maps.model.LatLng mLocation;

    // ...

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeDouble(mLocation.latitude);
        out.writeDouble(mLocation.longitude);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        mLocation = new LatLng(in.readDouble(), in.readDouble());
    }
}

答案 1 :(得分:2)

您可以查看ObjectOutputStream

首先,您必须为对象创建一个替代品:

    public class SerializableLatLng implements Serializable {

    //use whatever you need from LatLng

    public SerializableLatLng(LatLng latLng) {
        //construct your object from base class
    }   

    //this is where the translation happens
    private Object readResolve() throws ObjectStreamException {
        return new LatLng(...);
    }

}

然后创建一个合适的ObjectOutputSTream

public class SerializableLatLngOutputStream extends ObjectOutputStream {

    public SerializableLatLngOutputStream(OutputStream out) throws IOException {
        super(out);
        enableReplaceObject(true);
    }

    protected SerializableLatLngOutputStream() throws IOException, SecurityException {
        super();
        enableReplaceObject(true);
    }

    @Override
    protected Object replaceObject(Object obj) throws IOException {
        if (obj instanceof LatLng) {
            return new SerializableLatLng((LatLng) obj);
        } else return super.replaceObject(obj);
    }

}

然后在序列化时必须使用这些流

private static byte[] serialize(Object o) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new SerializableLatLngOutputStream(baos); 
    oos.writeObject(o);
    oos.flush();
    oos.close();
    return baos.toByteArray();
}