我正在尝试使用JavaCompiler类:
当我调用ToolProvider.getSystemJavaCompiler()时,它返回null.
我想这是因为我使用的是JRE而不是JDK.
问题是我希望它在所有平台上运行,无论用户使用JRE还是JDK的天气如何.
如果有人知道如何解决这个问题,或者使用其他方法请注释.
任何帮助,将不胜感激.
ToolProvider.getSystemJavaCompiler()不可用.
类路径中是否缺少tools.jar?
Set class path to the tools.jar
可以在jdk\jre目录中找到的文件.
System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_02");
小智 5
没有安装JDK时,这是从应用程序运行Java编译器的方法。
首先,将JDK中的tools.jar文件包含在Java应用程序中,然后将tools.jar放入类路径中。Oracle可能不喜欢您这样做。但是,存在法律解决方法。您可以从openjdk.org(openjdk),RedHat(IcedTea)或Azul Systems(Zulu)提供的免费JDK中获取tools.jar文件。
接下来,不要直接使用ToolProvider.getSystemJavaCompiler()和JavaCompiler类,而是直接调用tools.jar中的编译器。下面是代码片段:
String classpath = ...; // make sure tools.jar is in this path
String sourcepath = ...; // path to your sources
String putputpath = ...; // directory for generated class files
String filepath = ...; // file path the file you want to compile
String[] args = new String[] {
"-classpath", classpath,
"-sourcepath", sourcepath,
"-d", putputpath,
filePath
};
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
int compileStatus = javac.compile(args);
Run Code Online (Sandbox Code Playgroud)