Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 I can make that LatLng class implement Serializable?

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

    // ...
}

I don't want to declare mLocation transient.

like image 572
Jens Kohl Avatar asked Jan 08 '13 17:01

Jens Kohl


People also ask

How do you serialize a non serializable class?

You can't serialise a class that doesn't implement Serializable , but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way. First, make your non-serialisable field transient .

How do you serialize an object that does not implement serializable?

If Address is null, you can serialize the whole employee even if Address 's type is not serializable. If you mark Address as transient, it will skip trying to serialize Address . This may solve your problem.

How do you not allow serialization of attributes of a class in Java?

There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods.

How do you make a field serializable in Java?

By making a field Public It is one of the simplest ways by which we can make a field serialize and de-serialize. In this way, we simply make the field public for this. We will declare a class with a public, a protected and a private field. By default, only the available field will be serialized to JSON.


1 Answers

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());
    }
}
like image 97
Ian Roberts Avatar answered Oct 19 '22 08:10

Ian Roberts