2013-01-08 34 views
10

Tôi đang sử dụng Google's LatLng class từ Dịch vụ Google Play v2. Lớp cụ thể đó là cuối cùng và không thực hiện java.io.Serializable. Có cách nào để tôi có thể thực hiện lớp học LatLng triển khai Serializable không?Làm cách nào để tuần tự hóa lớp cuối cùng không thể tuần tự hóa của bên thứ ba (ví dụ: lớp LatLng của google)?

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

    // ... 
} 

Tôi không muốn khai báo mLocationthoáng.

+0

tìm một số cách giải quyết – UDPLover

Trả lời

25

Nó không phải là Serializable nhưng nó là Parcelable, nếu đó sẽ là một tùy chọn thay thế. Nếu không bạn có thể xử lý các serialization mình:

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

Cảm ơn câu trả lời của bạn; nó làm việc cho tôi. –

2

Bạn có thể có một cái nhìn tại ObjectOutputStream.

Trước tiên, bạn sẽ phải tạo một sự thay thế thả-in cho đối tượng của bạn:

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

} 

Sau đó tạo một thích hợp 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); 
    } 

} 

Sau đó, bạn sẽ phải sử dụng những con suối khi 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(); 
} 
Các vấn đề liên quan