【发布时间】:2019-06-26 10:36:10
【问题描述】:
代码使用 JDK 8 (1.8.0_212) 编译良好,但无法使用 JDK 11 (11.0.3) 编译 Oracle jdk 和 open jdk (aws corretto)
尝试使用 javac 和 Maven(maven 版本 3.6.1 和 maven-compiler-plugin 版本 3.8.0)进行编译,它可以针对 JDK 8 进行编译,但针对 JDK 11 会失败。
import java.net.URL;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Stream;
public class AppDemo {
public static void main(String[] args) {
// NO error here
giveMeStream("http://foo.com").map(wrap(url -> new URL(url)));
List<String> list = new ArrayList<String>();
list.add("http://foo.com/, http://bar.com/");
// error: unreported exception MalformedURLException;
// must be caught or declared to be thrown
list.stream().flatMap(
urls -> Arrays.<String>stream(urls.split(",")).map(wrap(url -> new URL(url)))
);
// error: unreported exception MalformedURLException;
// must be caught or declared to be thrown
Stream.concat(
giveMeStream("http://foo.com").map(wrap(url -> new URL(url))),
giveMeStream("http://bar.com").map(wrap(url -> new URL(url))));
}
static Stream<String> giveMeStream(String s) {
return Arrays.stream(new String[]{s});
}
static <T, R, E extends Throwable> Function<T, R>
wrap(FunException<T, R, E> fn) {
return t -> {
try {
return fn.apply(t);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
};
}
interface FunException<T, R, E extends Throwable> {
R apply(T t) throws E;
}
}
错误:
Expected : No compilation error
Actual : compilation error for JDK11
Error message with JDK 11:
s.<String>stream(urls.split(",")).map(wrap(url -> new URL(url)))
^
AppDemo.java:24: error: unreported exception MalformedURLException; must be caught or declared to be thrown
giveMeStream("http://foo.com").map(wrap(url -> new URL(url))),
^
AppDemo.java:25: error: unreported exception MalformedURLException; must be caught or declared to be thrown
giveMeStream("http://bar.com").map(wrap(url -> new URL(url))));
^
3 errors
【问题讨论】:
-
您忘记包含实际错误?
-
您好,我从错误的文件中发布了代码,如何更新代码?
-
@Fazal 点击帖子底部的编辑(标签下方)
-
@Karthikeyan Vaithilingam 谢谢,我已经编辑了代码,添加了编译错误。
-
似乎是类型推断问题。使用
(String url) -> new URL(url)解决它。作为旁注,您可以使用Stream.of(s)代替Arrays.stream(new String[]{s}),这会使giveMeStream方法过时。所以你可以使用Stream.of("http://foo.com", "http://bar.com").map(wrap(URL::new)) …