该代码在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
(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)) …
- Holger