5

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Ryker.Wang
  • 757
  • 1
  • 9
  • 18

4 Answers4

6

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)
Thilo
  • 257,207
  • 101
  • 511
  • 656
4

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You can try this work around:

public static <T extends Object> void test(ArrayList<T> list){
        if(null!=list && !list.isEmpty())        
                System.out.println(list.get(0).getClass().getName());
}
Viral Patel
  • 8,506
  • 3
  • 32
  • 29
  • 1
    this doesn't work if (1) the list is empty (even though you cased it out so it doesn't crash, it still fails to solve the task), (2) the first element is null, or (3) the first element's class is actually a subclass of T, which will give you the wrong answer – newacct Jan 06 '12 at 08:02
0

It seems you can with little wrapping your 'T' or Eraser. Here is SO discussion related to this. Get instance of generic type

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167