ToString () is a generic type in Java

How can I print a java generic type type?

Reflection? Any tricks?

public class Foo<K> {

    private K element;

    @Override
    public String toString() {
        return "Type: " + K;
    }
}
+5
source share
2 answers

element.getClass().getSimpleName()will probably do what you expect.

+6
source

Due to the erasure type, you may not know what the type parameter was when building the class. But you can use element.getClass()to get the runtime type of an element (which is probably a subclass of the type parameter, although it is not guaranteed - maybe uncontrolled selection).

, . , Guice . , Foo, : Foo<Integer> foo = new Foo<Integer>(){}; ( {}, Foo), type ParameterizedType type = (ParameterizedType) foo.getClass().getGenericSuperclass(), ParameterizedType. API Java, Guice.

+6

All Articles