Consider the following class:
public class Foo extends Exception implements CharSequence {
//...
}
The class Foo
implements both Throwable
and CharSequence
. So in case E
is set to this instance, the Java compiler does not know which method to call.
The reason there is probably no problem for Java7 is that generics are less implemented. In case you don't provide an E
yourself (e.g. (Foo) bar()
), Java will fall back on the basic verion of E
which is implements Exception
, E
is thus only considered to be an instance of Exception
.
In Java8, the type inference is improved, the type of E
is now derived from the parameter called for by then()
, in other words the compiler first looks what possible types then()
needs, the problem is that they both are valid choices. So in that case it becomes ambiguous.
Proof of concept:
Now we will slightly modify your code and show how ambiguous calls are resolved:
Say we modify the code to:
public class Main {
public static void main(String... args){
then(bar()); // Compilation Error
}
public static <E extends Exception> E bar() {
return null;
}
public static void then(CharSequence actual) {
System.out.println("char");
}
}
If you run this in Java8, there is no problem (it prints char
), because Java8 simply assumes there is such class Foo
(it created some kind of "inner" type for it that derived from both).
Running this in Java7 yields problems:
/MyClass.java:18: error: method then in class MyClass cannot be applied to given types;
then(bar()); // Compilation Error
^
required: CharSequence
found: Exception
reason: actual argument Exception cannot be converted to CharSequence by method invocation conversion
1 error
It did a fallback on Exception
and couldn't find a type that could deal with it.
If you run the original code in Java8, it will error because of the ambiguous call, if you run it in Java7 however, it will use the Throwable
method.
In short: the compiler aims to "guess" what E
is in Java8, whereas in Java7 the most conservative type was picked.