Eydwales
Eydwales

Reputation: 321

Java reflection, get the name of a generic class parameter

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 !

Upvotes: 0

Views: 194

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

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);

Upvotes: 3

Related Questions