11

我正在使用来自 v2 Google Play 服务的Google 的 LatLng 类。该特定类是 final 并且没有实现java.io.Serializable. 有什么办法可以让那个LatLng类实现Serializable吗?

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

    // ...
}

我不想声明mLocation transient

4

2 回答 2

30

它不是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());
    }
}
于 2013-01-08T17:29:09.120 回答
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();
}
于 2013-01-08T17:35:36.193 回答