内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
以下代码使用Java 8编译,但不使用Java 9编译:
public class CompileErrJdk9 {
@FunctionalInterface public interface Closure<R> {
R apply();
}
@FunctionalInterface public interface VoidClosure {
void apply();
}
static <R> R call(Closure<R> closure) {
return closure.apply();
}
static void call(VoidClosure closure) {
call(() -> { closure.apply(); return null; });
}
static <T> void myMethod(T data) {
System.out.println(data);
}
public static void main(String[] args) {
call(() -> myMethod("hello")); //compile error in jdk9
}
}
这是错误:
CompileErrJdk9.java:24: error: incompatible types: inference variable R has incompatible bounds
call(() -> myMethod("hello")); //compile error in jdk9
^
upper bounds: Object
lower bounds: void
where R is a type-variable:
R extends Object declared in method <R>call(Closure<R>)
1 error
我已经收窄至类型参数<T>
的myMethod
; 如果我放下它并Object
用于代码编译的参数类型。即使我没有使用type参数,也声明myMethod
为static <T> void myMethod() { }
失败(仅限于9)。
我检查了Java 9发行说明并搜索了有关此行为的解释,但未找到任何内容。我是否正确地认为这是JDK9中的错误,或者我错过了什么?