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

前端 未结 2 1595
礼貌的吻别
礼貌的吻别 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 05:04

    You can have a look at ObjectOutputStream .

    First, you'll have to create a drop-in replacement for your object :

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

    Then create an appropriate 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);
        }
    
    }
    

    Then you'll have to use these streams when serializing

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

提交回复
热议问题