gpt4 book ai didi

java - 如何使用 JavaCompiler 获取编译错误信息

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:10:00 69 4
gpt4 key购买 nike

这是我用来编译 java 类的代码:

public void javaCompile(String fileName) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager
.getJavaFileObjectsFromStrings(Arrays.asList(fileName));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
null, compilationUnits);
boolean success = task.call();
fileManager.close();
System.out.println("Success: " + success);
}

问题是我想收到有关出现的错误的更多信息(不仅仅是成功:错误)。有人可以帮助我吗?

最佳答案

如果您只想在控制台中打印错误,请不要使用 diagnosticsCollector,如下所示:

    public void javaCompile(String fileName) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null/*diagnostics*/, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager
.getJavaFileObjectsFromStrings(Arrays.asList(fileName));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null/*diagnostics*/, null,
null, compilationUnits);
boolean success = task.call();
fileManager.close();
System.out.println("Success: " + success);
}

如果您想以编程方式分析错误,请使用:

public void javaCompile(String fileName) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(fileName));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, compilationUnits);
boolean success = task.call();
if (!success) {
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
// read error dertails from the diagnostic object
System.out.println(diagnostic.getMessage(null));
}
}
fileManager.close();
System.out.println("Success: " + success);
}

关于java - 如何使用 JavaCompiler 获取编译错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295873/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com