toString() a generic type in Java

后端 未结 2 945
一个人的身影
一个人的身影 2021-01-06 02:50

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

Reflection? Any tricks?

public class Foo {

    private K element;

    @Override
    publi         


        
相关标签:
2条回答
  • 2021-01-06 03:35

    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.

    0 讨论(0)
  • 2021-01-06 03:38

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

    0 讨论(0)
提交回复
热议问题