0

I would like to get the name of a generic parameter of a class. For instance :

public class A<B> {
...
}

and in this class i would like to the name of the class B. Like :

A<Solution> var = new A<Solution>();

I would like to have a way to have the String "Solution" somewhere in a method of A

If you have any idea i am here :)

Thank you !

0

1 Answer 1

3

You would need to pass in the Class instance as a constructor parameter:

class A<B> {
  private final Class<B> clazz;

  A(Class<B> clazz) {
    this.clazz = clazz;
  }

  String getName() {
   return clazz.getSimpleName();
  }
}

A<Solution> var = new A<>(Solution.class);
Sign up to request clarification or add additional context in comments.

5 Comments

You can also get it by subclassing A. See Guava's TypeToken or Jackson's TypeReference for examples.
@shmosel that would be an appropriate solution if B needs to be generic. Would you consider adding that as another answer?
You need to have an explicit type either way, e.g., new A<Solution>() {}. It's just a bit cleaner, especially if you need to capture multiple type parameters.
@shmosel Yes. But it's a different approach (it's the inheritance approach, whereas mine is the compositional approach), so you should add it as an alternative answer.
I don't have the patience to write it up now. Feel free to do so.

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.