Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString() a generic type in Java

Tags:

java

generics

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;
    }
}
like image 246
David Robles Avatar asked Apr 01 '10 00:04

David Robles


People also ask

What is toString () in Java?

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.

What type of method is toString ()?

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.

Is toString a default method in Java?

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.

What is generic type casting in Java?

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.


1 Answers

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

like image 163
harto Avatar answered Oct 11 '22 19:10

harto