JDK 11编译失败,JDK 8编译正常

时间:2019-06-26 10:36:10

标签: java java-8 java-11

该代码可以在JDK 8(1.8.0_212)上正常编译,但无法在Oracle jdk和open jdk(aws corretto)上都使用JDK 11(11.0.3)进行编译

尝试使用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

1 个答案:

答案 0 :(得分:1)

可能是因为对规范进行了细微更新。有关系吗?这样是行不通的。

在这里将抛出的异常转换为参数化类型没有实际目的。另外,您将使用此代码制作configure的链。试试这个,代替:

RuntimeException

现在它将可以正常编译。

给读者:不要这样做。处理Java规则(如检查的异常)的正确方法是处理它们。使用骇客来绕开语言的本质只是意味着您的代码是非惯用的(其他阅读您的代码的人不会理解它,并且您将很难阅读其他人的代码。这很糟糕),往往与其他库互操作的方式很糟糕,现在应该会有所帮助的各种功能受到损害(例如:在这里,您会得到很多因果异常链,这些异常链使读取日志和异常跟踪变得更加困难)。同样,远离“人迹罕至的地方”会导致有趣的时期,例如用于编译的代码不再编译。

相关问题