How to serialize a third-party non-serializable final class (e.g. google's LatLng class)?

前端 未结 2 1611
礼貌的吻别
礼貌的吻别 2021-01-02 04:33

I\'m using Google\'s LatLng class from the v2 Google Play Services. That particular class is final and doesn\'t implement java.io.Serializable. Is there any way

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-02 04:45

    It's not Serializable but it is Parcelable, if that would be an option instead. If not you could handle the serialization yourself:

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

提交回复
热议问题