Why does javac not abort with a type error on this code example
import java.util.List;
public class StaticMethodWithBoundedReturnType {
static class Foo {
}
static class Bar extends Foo {
}
static <F extends Foo> F getFoo(String string) {
…
}
public static void main(String[] args) {
// Compiles without error, even though List does not extend Foo.
List<Integer> list = getFoo("baz");
}
}
Obviously List can never be a subtype of Foo. And even if there would exists a subtype of List which would somehow extend Foo, then the assigning of list at the call site of getFoo() should be invalid. I'm aware of the existence of type erasure. But shouldn't javac be able see that the type of list does not satisfy the bounded type constraint extends Foo and thus fail compilation with a type error?
Why is javac not able to typecheck the call site of a static method with a bounded type parameter as return type?
It appears I could get type safety with the following slight modification:
import java.util.List;
public class StaticMethodWithBoundedReturnType {
static class Foo {
}
static class Bar extends Foo {
}
static <F extends Foo> F getFoo(String string, Class<F> clazz) {
…
}
public static void main(String[] args) {
// Does not compile \o/
List<Integer> list = getFoo("baz", List.class);
}
}
But this requires adding the Class parameter to getFoo() which isn't used in the method's body at all. Is there a better way to achieve type safety?