2

I'm working with Spring, and we are going to pass the ApplicationContext to a POJO as it is part of our strategy.

I have to retrieve beans this way:

context.getBean(MyService.class);

But we also have services that accept generics, and we want to do something like:

context.getBean(MyService<String>.class) //doesn't compile
//how can I get the class of MyService<String>??

How can I get the class of an object that is parametrized with generic arguments?

AFP_555
  • 2,392
  • 4
  • 25
  • 45

1 Answers1

0

Careful with type erasure if you want something like ParameterizedTypeReference<C>

String[] beanNames = applicationContext.getBeanNamesForType(ResolvableType.forType(new ParameterizedTypeReference<String>() {}));
if (beanNames.length > 0) {
    String bean = (String) applicationContext.getBean(beanNames[0]);
}
Radu
  • 2,022
  • 3
  • 17
  • 28