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.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
But ArrayList is a parameterized type. A parameterized type can take a type parameter, so that from the single class ArrayList, we get a multitude of types including ArrayList<String>, ArrayList<Color>, and in fact ArrayList<T> for any object type T.
Java List is an ordered collection. Java List is an interface that extends Collection interface. Java List provides control over the position where you can insert an element. You can access elements by their index and also search elements in the list.
formal parameter — the identifier used in a method to stand for the value that is passed into the method by a caller. actual parameter — the actual value that is passed into the method by a caller. For example, the 200 used when processDeposit is called is an actual parameter.
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 getClass
on 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 usedYou cannot, because of type erasure in the implementation of Java generics. When you need to know the class, the typical trick is to pass Class as a separate parameter called "type token", like this:
public static <T extends Object> void test(ArrayList<T> list, Class<T> classType) {
}
This trick is discussed at some length in the tutorial on Java generics (see the bottom of the page for an example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With