简体   繁体   中英

How to get ClassLoader from type variable (for parceling a class using generics)

I have a parcelable class with a generic type object. Usually I would read out that object like this:

in.readParcelable(MyParcelableClass.class.getClassLoader())

Apparently I can't do that with a generic type variable.. see code below. Can anyone point me into the right direction?

public class ParcelableOverlayItem<T extends Parcelable> extends OverlayItem implements Parcelable {

  private T parcelableTypeObject;

  protected ParcelableOverlayItem(Parcel in) {
    this(in.readParcelable(T.class.getClassLoader())); // this is not working: "Cannot select from a type variable"
  }

  public void writeToParcel(Parcel dest, int flags) {
    dest.writeParcelable(parcelableTypeObject, flags);
  }

  public ParcelableOverlayItem(T parcelableTypeObject) {
    super();
    this.parcelableTypeObject = parcelableTypeObject;
  }

  public T getParcelableTypeObject() {
    return parcelableTypeObject;
  }

  // ...
}

您可以像这样从泛型类型T获取ClassLoader

this(in.readParcelable(parcelableTypeObject.getClass().getClassLoader()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM