tags:

views:

79

answers:

2

How can I print the type of a generic java type?

Reflection? Any tricks?

public class Foo<K> {

    private K element;

    @Override
    public String toString() {
        return "Type: " + K;
    }
}
+4  A: 

element.getClass().getSimpleName() will probably do what you are expecting.

harto
Would K.class.getSimpleName() also do the trick? It's over 10 years since I java'd so I missed generics. I might be wrong.
spender
But if the element variable is not initialised, is there any other way of getting the type without getting a null pointer exception?
davidrobles
K.class will not work (probably not even compile). And yes, you need to null-check. And no, there is no other way because of type erasure (no runtime information about K unless you store it yourself).
Thilo
@davidrobles hmm. Not sure, actually
harto
+2  A: 

Because of type erasure, you can't know that what was the type parameter when the class was constructed. But you can use element.getClass() to get the runtime type of the element (which is probably a subclass of the type parameter, although it's not guaranteed - there could have been an unchecked cast).

However, there are some tricks that enable access to the type parameters. There are some tricks that Guice can do. Also if you create a subclass of Foo, like this: Foo<Integer> foo = new Foo<Integer>(){}; (notice the {} which makes it an anonymous subclass of Foo), then it's possible to get access to the type parameter with ParameterizedType type = (ParameterizedType) foo.getClass().getGenericSuperclass() and then calling the methods of ParameterizedType. This is the feature of Java's reflection API that also Guice takes advantage of.

Esko Luontola