Java 9 无 class 定义异常

Java 9 no class definition exception

所以我想试试 http 客户端

package com.company;

import jdk.incubator.http.HttpClient;

public class Main {

public static void main(String[] args) {
    HttpClient client =  HttpClient.newHttpClient();

  }
}

我的模块信息如下所示

module com.company {
    requires jdk.incubator.httpclient;
}

但是我明白了 java.lang.NoClassDefFoundError: jdk/incubator/http/HttpClient

而且我真的不明白为什么。我的 java 版本是 "build 9-ea+ 169" 并且我使用的是最新版本的 IntelliJ idea (2017.1.3)。我查看了 答案,看起来我必须将要求添加到文件中,但由于某种原因它不起作用。

如果我使用 --add-modules jdk.incubator.httpclient 作为启动参数,

对我来说工作正常。

HttpClient client = HttpClient.newHttpClient();
client.executor().execute(() -> System.out.println("Here")); // prints Here

如果你说你的模块需要它,并不意味着它会被包含;默认情况下不包含它。

一定是你或 IntelliJ 搞错了。您正在使用 incubator module,关于它的文档说:

Incubator modules are part of the JDK run-time image produced by the standard JDK build. However, incubator modules are not resolved by default for applications on the class path. Applications on the class path must use the --add-modules command-line option to request that an incubator module be resolved. Applications developed as modules can specify requires or requires transitive dependences upon an incubator module directly.

我刚刚在 java-9-ea+169 上确认了该行为,即我可以编译和启动这样的模块(从命令行)而无需其他标志。

您没有收到编译错误这一事实似乎表明 IntelliJ 在编译中正确地包含了模块声明。您收到 运行 次错误并且 帮助的事实表明 JVM 没有看到您作为模块启动的代码。

我运行陷入同样的​​问题

java.lang.NoClassDefFoundError: jdk/incubator/http/HttpClient

使用 java-9-ea+173 和 IntelliJ。我遵循 Eugenes 和 Nicolais 的建议,通过 Run/Debug 配置中的 --add-modules jdk.incubator.httpclientjdk.incubator.httpclient 显式添加到模块路径(在 macOS 上:Menu Bar -> Run -> Edit Configurations -> Configuration Tab -> VM Options -> --add-modules jdk.incubator.httpclient

之后一切正常。当然,您必须像之前所说的那样将依赖项添加到 module-info.java 中:

module network {
    requires jdk.incubator.httpclient;
}

更新:

使用最新的 IntelliJ IDEA 2017.2 EAP 172.2953.9 ,我不需要将 --add-modules 放入 VM 选项。它开箱即用。