i have 2 classes:
public class Super {
public static <T> T bar(Class<T> clazz){
try {
return (T)(clazz.newInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
}
and
public class Sub extends Super{
public static void main(String[] args){
Sub s = Sub.bar(Sub.class);
}
}
now i don’t want to use Class<T> clazz as a param of bar, so how can i return the generic type T, thanks.
You can’t. Generics are only compile-time and are not available run-time. Thus, you’ll have to provide the
Class clazzin order to know the T at runtime.