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

Jen*_*ohl 11 java serialization

我在v2 Google Play服务中使用Google的LatLng课程.那个特定的类是最终的,并没有实现java.io.Serializable.有什么方法可以让这个LatLng类实现Serializable吗?

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我不想申报mLocation 瞬态.

Ian*_*rts 29

它不是,SerializableParcelable如果那将是一个选择.如果没有,您可以自己处理序列化:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)