2

I have a generic class like this:

public class MyClass<T> {
    private T var;

    public MyClass(T init_value) {
        var=init_value;
    }

    ...
}

Now I would like to add toString() method to it, which returns the concrete type and value of var. I try something like this:

public String toString() {
    return String.format("MyClass object initialized with type %s and value %s", T, var);
}

This, however, does not work, as I have a problem that type variable T seems not to be visible as normal variable. Namely, I get an error:

T cannot be resolved to a variable

How can I overcome this problem and make a type variable printable?

Roman
  • 2,225
  • 5
  • 26
  • 55

1 Answers1

2

As you already have object of class T you can use getClass on it:

String.format("MyClass object initialized with type %s and value %s", var.getClass().getSimpleName(), var);

If you don't have var, you option would be to provide argument of type Class<T> explicitly:

public class MyClass<T> {
    private Class<T> clazz;

    public MyClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public String toString() {
        return String.format("Type of T: %s", clazz.getSimpleName());
    }
}

You have to do this, because type T is usually not accessible in runtime due to type erasure. The only exception is when you define class that extends explicitly parameterized class: class MyIntegerClass extends MyClass<Integer>. In this case type parameters could be accessed via reflection.

Community
  • 1
  • 1
Aivean
  • 10,692
  • 25
  • 39