Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }

  // ...
}
like image 674
Blacklight Avatar asked Feb 26 '14 12:02

Blacklight


People also ask

How do you find the class type of a variable?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you declare a generic type in a class explain?

If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section.

Which types can be used as arguments of generics?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

Can generics be used with inheritance in several ways what are they?

Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.


1 Answers

You can get the ClassLoader from generic type T like this

this(in.readParcelable(parcelableTypeObject.getClass().getClassLoader()));
like image 146
Gopal Gopi Avatar answered Oct 23 '22 18:10

Gopal Gopi