在Java 9+中使用JRE运行时,我可以提供运行时编译器访问吗?

rai*_*lin 5 java java-platform-module-system java-9 java-10 jmod

我正在将应用程序迁移到Java 10.我们的应用程序通常使用JRE运行,但我们允许用户通过捆绑tools.jar和使用反射来JavacTool按需加载实例来编译自己的自定义代码.我们的方法如下:

public static JavaCompiler getJavaCompiler() {
    String toolJarName = "tools.jar";
    File file = getResourceForClass("tools.jar");
    try {
        file = file.getCanonicalFile();
    } catch (IOException ignore) {
    }
    if (!file.exists())
        throw new RuntimeException("Can't find java tools file: '"+file+"'");
    try {
        URL[] urls = new URL[]{ file.toURI().toURL() };
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        return Class.forName("com.sun.tools.javac.api.JavacTool", false, cl).asSubclass(JavaCompiler.class).newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Can't find java compiler from '"+file+"': "+e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是必要的,因为javax.tools.ToolProvider.getSystemJavaCompiler()从JRE运行时返回null.我们的方法在Java 8中运行良好,但tools.jar在Java 9中被删除了,我需要的类com.sun.tools.javac.api.JavacTooljdk.compiler模块中,它仍然是JDK的一部分,而不是JRE.

jdk.compiler启动JRE时是否有任何方法可以加载模块?我怀疑它不是,基于这个答案,我尝试使用--add-module结果: java.lang.module.FindException: JMOD format not supported at execution time

我还缺少另一种解决方案吗?

man*_*uti 4

在我看来,解决问题的最简单方法是保持简单并要求用户下载 JDK 而不是 JRE:

...但我们允许用户编译自己的自定义代码

用户下载 JDK 应该不会感到意外,因为他们正在使用 JDK 的一个功能:编译代码。

如果这是不可能的,那么您可能想尝试jlink@nullpointer 在评论中建议的解决方案。

  • 有了 Java 11,这个解决方案变得非常简单,因为不再需要 JRE。那些知道如何创建较小的运行时环境的人应该知道如何包含编译器。 (2认同)