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

我在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 瞬态

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

您可以查看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(); }