Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve conversion from List<SomeParamType> to List<SomeParamType<?>>

Tags:

java

generics

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?

like image 860
Marko Topolnik Avatar asked Jan 09 '15 10:01

Marko Topolnik


2 Answers

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;
}
like image 145
Raffaele Avatar answered Nov 08 '22 02:11

Raffaele


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.

like image 1
Konstantin Yovkov Avatar answered Nov 08 '22 00:11

Konstantin Yovkov