0

I have a parameterized class. I would like to get the name of the class represented by the class name. For instance, what I want to do is this:

public T foo(){
    System.out.println(T.class.getName());
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Thom
  • 14,013
  • 25
  • 105
  • 185

3 Answers3

2

You can't do it this way, since T isn't known at compile time. You could achieve something similar like so:

public void foo(T t) {
    System.out.println(t.getClass().getName());
}

Note that this takes an instance of T and would print out the name of its dynamic type.

Whether or not this is a good enough substitute depends on your use case.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Java generics don't work that way. If you have any bounds on T, you can access the bounds by querying the type variable definition. E.g.:

public class Foo<T extends Bar>{}

will let you get at Bar, but not at the subtype of Bar you are actually using. It doesn't work, sorry.

Read the Java Generics FAQ for more info.

BTW: One common solution to this problem is to pass the subtype of T into your class, e.g.

public T foo(Class<? extends T> tType){
    System.out.println(tType.getName());
}

I know it's cumbersome, but it's all Java generics allow.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Actually, you can get what `T` is. See my answer for how. (Not sure why it was downvoted!) – ziesemer Jan 24 '12 at 01:18
  • @ziesemer you can only get at bounds that are actually there. If the above T was declared `T extends Something`, you could get at the something part. But if your type variables have no bounds there's nothing to get at. – Sean Patrick Floyd Jan 24 '12 at 07:30
0
public T foo(T t){
    System.out.println(t.getClass().getName());
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142