要使用JDK的Java编译器API, 需要遵循以下步骤:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.DiagnosticCollector;
import javax.tools.Diagnostic;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject.Kind;
import javax.lang.model.SourceVersion;
import java.util.Arrays;
import java.util.List;
import java.io.File;
import java.io.Writer;
import java.io.PrintWriter;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
JavaFileObject sourceFile = fileManager.getJavaFileForInput("Main", "Main.java", Kind.SOURCE);
List<String> options = Arrays.asList("-d", "output");
List<JavaFileObject> sourceFiles = Arrays.asList(sourceFile);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sourceFiles);
Boolean result = task.call();
if (result) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation failed");
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic);
}
}
fileManager.close();
这样就可以使用JDK的Java编译器API来编译Java源文件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。