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());
}
2

3 Answers 3

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.

2
  • In addition, this gives you the name of the class of t, which could be a subclass of the type parameter.
    – Stephen C
    Jan 23, 2012 at 14:16
  • @StephenC: This is what I meant by "dynamic type".
    – NPE
    Jan 23, 2012 at 14:19
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.

2
  • Actually, you can get what T is. See my answer for how. (Not sure why it was downvoted!)
    – ziesemer
    Jan 24, 2012 at 1: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. Jan 24, 2012 at 7:30
0
public T foo(T t){
    System.out.println(t.getClass().getName());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.