是的你可以。您只需要在构建子类对象期间存储类名或类加载器,然后您可以在 Parcelable 的读/写操作期间传递它。
分步说明:
步骤 1。存储从您的 Generic 类扩展的类名,如下所示:
public abstract class GenericClass<T> implements Parcelable {
private String className;
步骤 2。从泛型类扩展的任何类都必须在构造过程中指定类名,如下所示:
public class MyClass extends GenericClass<MyClass> {
public MyClass () {
super();
setClassName(MyClass.class.getName()); // Generic class setter method
}
步骤 3。在您的通用类中,您可以像这样读取/写入您的类名到 getClassLoader() :
public abstract class GenericClass<T> implements Parcelable {
private String className;
T myGenericObject;
protected MyClass (Parcel in) {
super(in);
this.className = in.readString();
ClassLoader classLoader;
try {
classLoader = Class.forName(this.className).getClassLoader();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
myGenericObject = in.readParcelable(classLoader);
//... Other class members can go here
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(className);
//... Other class members can go here
}
}