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?

1
  • Think about <T> like it's alias. So what should be <T> to make your code compile? Commented Aug 22, 2015 at 9:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.