Is there a way to get Class object from the type variable in Java generic class? Something like that:
public class Bar extends Foo {
public Clas
This code works for derived classes as well:
import java.lang.reflect.ParameterizedType;
public abstract class A<B>
{
public Class<B> getClassOfB() throws Exception
{
ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
return (Class<B>) superclass.getActualTypeArguments()[0];
}
}
snagged from here: https://stackoverflow.com/a/4699117/26510
The code snippet is a bit confusing. Is T a type parameter or a class?
public static class Bar extends Foo<String> {
public Class<?> getParameterClass() {
return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
public static class Bar2<T> extends Foo<T> {
public Class<?> getParameterClass() {
return (Class<?>) (((ParameterizedType)Bar2.class.getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
public static void main(String[] args) {
System.out.println(new Bar().getParameterClass());
System.out.println(new Bar2<Object>().getParameterClass());
}
Actually the second println will cause an exception.
This works:
public static class Bar extends Foo<String> {
public Class<?> getParameterClass() {
return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
}
}