While using Spring ApplicationContext and its method getBeansOfType
I have run into an issue with generic types. This demonstrates the problem:
class Test
{
List<Generator<?>> allGenerators =
new ArrayList(getBeansOfType(Generator.class).values()); // Raw type warning
// for new ArrayList()
<T> Map<String, T> getBeansOfType(Class<T> klass) {
return emptyMap();
}
}
interface Generator<R> {}
I retrieve all beans of a parameterized type from the container. I want to have them as Generator<?>
and use custom logic to safely cast to the appropriate type parameter based on a property on each Generator
instance.
My problem is that I can't find any way to assign to allGenerators
without type safety warnings, even though on a conceptual level I am not committing to any unchecked type parameter. I just want to convert a raw type to a wildcard type.
Is there any idiom which does not require @SuppressWarnings
to get there?
Not actually a conversion, but a program that builds a list of the required type without warnings:
public List<Generator<?>> solution() {
List<Generator<?>> dst = new ArrayList<>();
for (Generator<?> g : getBeansOfType(Generator.class).values()) {
dst.add(g);
}
return dst;
}
I suppose it's not possible (to convert a raw type to an one with a wildcard parameter).
The reason is that the generic type (and in particular, the wildcard) is something different than a class type and cannot be represented with the tools of class types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With