I'm in a position where I have to implement Parcelable interface on a class that has a custom field that could be any subclass of Shape class:
class MyClass implements Parcelable
{
Shape shape;
}
now, If I want to write the shape field to the parcel, it's very easy:
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeParcelable(shape, flags);
}
And that's fine, because the Shape object could be any object that extends Shape and it will write correctly.
But when I read the object from parcel, I must pass a ClassLoader of the instance class, but at that point I don't know what the actual instance should be. for Shape it could be a Triangle, Square, or a Circle.
@Override
public MyClass createFromParcel(Parcel source)
{
MyClass o = new Myclass();
o.shape = source.readParcelable(Shape.class); // ???
return o;
}
My current workaround is to use Serializable to write this object, but this is very inefficient. What would be the best way to solve this?