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.

Sign up to request clarification or add additional context in comments.

2 Comments

In addition, this gives you the name of the class of t, which could be a subclass of the type parameter.
@StephenC: This is what I meant by "dynamic type".
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 Comments

Actually, you can get what T is. See my answer for how. (Not sure why it was downvoted!)
@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.
0
public T foo(T t){
    System.out.println(t.getClass().getName());
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.