Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The parameter is ArrayList<T> and how can I get the T's className

Tags:

java

generics

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.

like image 839
Ryker.Wang Avatar asked Jan 06 '12 04:01

Ryker.Wang


People also ask

What is T type Java?

< 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.

Is ArrayList parameterized?

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.

What Does List <?> Mean in Java?

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.

What are formal type parameters in Java?

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.


2 Answers

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:

  • pass in a Class<T> parameter in addition to the list to tell the method about the type to be used
  • or look at the first element of the list (if present) and trust that its runtime type is representative enough (which it may not)
like image 87
Thilo Avatar answered Oct 01 '22 11:10

Thilo


You 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).

like image 20
Sergey Kalinichenko Avatar answered Oct 01 '22 10:10

Sergey Kalinichenko