A post I found with Ian Robertson has a great useful method for defining a runtime class for a Java class type parameter. It goes beyond the fast version:
ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
Class<?> c = (Class<?>) pt.getActualTypeArguments()[0]
Any method works like a charm for parameterized children inheriting from an abstract parameterized parent ( class Foo<T> extends Bar<T>), or an anonymous instance of a parameterized abstract class ( new Foo<Bar>() {}) and creates an instance with a specific type.
In case of failure, I try to do the same for another object created using the type parameter. The corresponding class objects are:
public class Foo {}
public class MyFoo extends Foo {}
public abstract class AbstractLoader<T extends Foo> {}
public abstract class AbstractReader<T extends Foo> {}
public class MyReader<T extends Foo> extends AbstractReader<T> {}
public class Loader<T extends Foo> extends AbstractLoader<T> {
public MyReader<T> getReader() {
return new MyReader<T>();
}
}
Code example:
static void main(String... s) {
Loader<MyFoo> loader = new Loader<>();
MyReader<MyFoo> = loader.getReader();
ParameterizedType pt = (ParameterizedType)loader.getClass().getGenericSuperclass();
System.out.println("LoaderType = " + pt.getActualTypeArguments()[0]);
pt = (ParameterizedType)reader.getClass().getGenericSuperclass();
System.out.println("ReaderType = " + pt.getActualTypeArguments()[0]);
}
, "" - , . OTOH, " " - .