1

Possible Duplicate:
How to determine the class of a generic type?

I have a method such as:

public <T> List<T> bar() {
    return new Baz<T.class>().toList();
}

T.class creates a compiler error. Is there some way to do this in Java, or is it impossible because of type erasure?

Community
  • 1
  • 1
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • You can do this just fine: `return new Baz().toList()`. There's no need for the method to know exactly what type `T` is at runtime in this case. – ColinD Jun 12 '11 at 22:24

2 Answers2

0

Type erasure prevents it. The best you can do is:

public <T> List<T> bar(Class<T> clazz) {
    // do something useful with the Class object
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

According to my limited knowledge this is undoable due to type erasure. However, some nice workarounds are given in this thread.

I would, however, see the non-workaround solution.

Community
  • 1
  • 1
Miki
  • 7,052
  • 2
  • 29
  • 39