Reputation: 93
I want to be able to dynamically compile a Java file and handle any compile errors and exceptions one by one. So I looked at JavaCompiler, and there's an example used to collect diagnostics:
Iterable<? extends JavaFileObject> compilationUnits = ...;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics())
System.out.format("Error on line %d in %d%n",
diagnostic.getLineNumber()
diagnostic.getSource().toUri());
fileManager.close();
This is all fine and dandy, except that the Diagnostic objects I get back are not very helpful in determining exactly what compile error occurred during compilation. There is a getMessage()
and getCode()
method that helps determine more specifics, but the API says:
The actual message is implementation-dependent.
Which seems not very useful for portability, and if I was to parse it, I'd be doing it in a round-about way. So I'm wondering if I'm missing something when reading the API, or is there a better alternative to the javax.tools
package.
Upvotes: 1
Views: 239
Reputation: 310936
You don't get exception stack traces from a compiler. If you did it would be a sign of an internal compiler failure, not a fault in your code. I don't know what you're expecting exactly but the diagnostic messages are about all there is.
Upvotes: 1