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.JavacTool在jdk.compiler模块中,它仍然是JDK的一部分,而不是JRE.
jdk.compiler启动JRE时是否有任何方法可以加载模块?我怀疑它不是,基于这个答案,我尝试使用--add-module结果:
java.lang.module.FindException: JMOD format not supported at execution time
我还缺少另一种解决方案吗?
在我看来,解决问题的最简单方法是保持简单并要求用户下载 JDK 而不是 JRE:
...但我们允许用户编译自己的自定义代码
用户下载 JDK 应该不会感到意外,因为他们正在使用 JDK 的一个功能:编译代码。
如果这是不可能的,那么您可能想尝试jlink@nullpointer 在评论中建议的解决方案。