The following Java 7 code compiles fine without type safety warnings:
@SuppressWarnings("javadoc")
public class Foo {
public static class Bar<T> {
public final Class<T> type;
public Bar(Class<T> type) {
this.type = type;
}
}
@SuppressWarnings("unused")
public static void main(String[] args) {
new Foo(
Arrays.asList(
new Bar<>(Object.class),
new Bar<>(String.class)));
}
public final List<Bar<?>> list;
public Foo(List<Bar<?>> list) {
this.list = list;
}
}
However, changing
new Bar<>(Object.class),
to
new Bar<>(String.class),
fails to compile with following error:
The constructor Foo(List<Foo.Bar<String>>) is undefined
Compiling with Java 8 succeeds. According to previous posts on StackOverflow
- Difference of assignability with nested wildcards in Java 7/8 generics
- Why does this compile in Java7 and does not in Java8?
there was some improvement in Java 8 which now allows this to compile.
The question is now what could be the best workaround for Java 7.
Adrian.