Is there a way to get the generic type of the following class at runtime (I will call doSomething()
at runtime):
class MyClass<D> extends BaseClass<List<D>> {
public Class<D> getGenericClass(){
Type [] ta = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
Class ty = (Class) ta[0]; // is java.util.List<D> and throws a cast exception
// TODO I want to know what kind of class "D" is
}
}
class BaseClass<T>
T data;
}
I would like to use the MyClass
as follows:
MyClass<Foo> instance = new MyClass<Foo>();
Class<Foo> foo = instance.getGenericClass();
The lines of code from above are just to show you the (simplified) scenario I'm facing. If I would instantiate it by hand, then I would already know that I'm using Foo
as generic parameter, but thats not the case.
FYI I'm trying to deal with Android Parcelable
and to get the correct class loader for readParcelable()
by using generics. Concrete: MyClass implements Parcelable
. While reading the Parcel
I have to specify a classloader like this data = parcel.readArrayList(Foo.class.getClassLoader)
and I want to determine that dynamically by using reflections like data = parcel.readArrayList(getGenericClass().getClassLoader())
Is there a way to get that kind of information?
Typically you would just use:
Class type = (Class) (getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
but that returns java.util.List<D>
, but I'm interested in what <D>
is. Is there a way to dive into that generic type as well?