I'm trying to create public class MyClass<T extends Parcelable> implements Parcelable
. I'm having trouble implementing Parcelable
. Is it possible to create a generic class that implements Parcelable
? (Note that T
is bounded so that it also must implement Parcelable
).
I am running into trouble with the fact that the Parcelable interface requires a static variable: public static final Parcelable.Creator<MyParcelable> CREATOR
. Thus I cannot do public static final Parcelable.Creator<MyClass<T>> CREATOR
because MyParcelable<T>
is nonstatic.
André
I had similar issues with implementing Parcelable on a class with a generic, the first issue was the same as what you were experiencing:
The second was to read in a Parcelable object you need access to the
ClassLoader
which cannot be gotten fromT
due to type erasure.The class below is an adaption of a class I am using in production which overcomes both issues. Note: I have not tested this class specifically, so let me know if you have any issues.
Yes you can. You just need to store the class name or class loader during the construction of your subclass object and then you can pass it during the read/write operation of the parcelable.
Step by step instructions:
Step 1. Store the class name that extends from your Generic class like this:
Step 2. Any classes that extends from your generic class must specify the class name during its construction like this:
Step 3. In your generic class, you can then read/write your class names to getClassLoader() like this:
}
Write the generic data member class name to the parcel and then read it back in order to create its class loader. Example,