0

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?

mick88
  • 852
  • 1
  • 8
  • 12

1 Answers1

4

It is OKAY to use Shape.class when you read your Parcelable as far as I know, since it will return an instance of the SubClass, which works fine as long as your sub classes of Shape implement the Parcelable method writeToParcel() on their own and also have their own CREATOR variables. The subclasses cannot rely on the CREATOR of Shape.

u3l
  • 3,342
  • 4
  • 34
  • 51