The parameter is ArrayList<T> how can I get the T’s className
public static <T extends Object> void test(ArrayList<T> list){
T temp;
Class classType=temp.getClass();
System.out.println(classType.getName());
}
It will be failed to compile that:he local variable temp may not have been initialized.
But how can I get the className of the template class.
You cannot get the generic type. This is due to how generics are implemented in Java (using type erasure). Basically, you can only use generics to catch type-errors at compile-time.
Your code fails to compile, because you are trying to call
getClasson a local variable that has not been initialized.What you could do instead is:
Class<T>parameter in addition to the list to tell the method about the type to be used