How to use JavaCompiler from tools.jar without JDK

帅比萌擦擦* 提交于 2021-01-28 08:52:15

问题


I am trying to create an application that can compile a provided .java file during runtime. I understand that there is a programmatical compiler available within the tools.jar of the JDK. However, I cannot guarantee that the user of the application has JDK. I have attempted to package tools.jar within the application and reference it as a library. This seems to work within the Eclipse IDE when I have tools.jar added into the Bootstrap Entries of the classpath. When exporting the application to a runnable jar (with tools.jar packaged with it), ToolProvider.getSystemJavaCompiler(); returns null. I am not exactly sure what the issue is, but I believe it may have to do with the Bootstrap Entries of the classpath not being properly preserved when the application is exported to a runnable jar. Any ideas? Are there any alternatives to the tools.jar compiler that I could use? Thanks for your patience, as this is my first question posted here!


回答1:


You need to use the compiler within "tools.jar"

ToolProvider.getSystemJavaCompiler()

will return the compiler from the jdk defined in the path variable, you can do this instead:

File file = new File(pathToToolsJar);
URL[] urls = new URL[]{ file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
Class compilerClass = loader.loadClass("com.sun.tools.javac.api.JavacTool");
JavaCompiler compiler = (JavaCompiler) compilerClass.getConstructor().newInstance();

Or you can add tools.jar as a library at compile time

import com.sun.tools.javac.api.JavacTool;
...
JavaCompiler compiler = new JavacTool();

Or you can change System properties, but that leads to unexpected behaviors



来源:https://stackoverflow.com/questions/53292291/how-to-use-javacompiler-from-tools-jar-without-jdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!