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;
}
}
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler.
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
The toString method is a built-in method in the Object class in java. Object class is present in java. lang package, and it's the parent class of all classes. Every class in Java inherits the default implementation of the toString method.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
element.getClass().getSimpleName()
will probably do what you are expecting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With