toString() a generic type in Java
How can I print the type of 开发者_如何学JAVAa generic java type?
Reflection? Any tricks?
public class Foo<K> {
private K element;
@Override
public String toString() {
return "Type: " + K;
}
}
element.getClass().getSimpleName()
will probably do what you are expecting.
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.
精彩评论