Skip to content

Instantly share code, notes, and snippets.

@ashkrit
Created August 11, 2020 10:48
Show Gist options
  • Save ashkrit/9ea9783c43f6667cccfc4bd8cbb06d69 to your computer and use it in GitHub Desktop.
Save ashkrit/9ea9783c43f6667cccfc4bd8cbb06d69 to your computer and use it in GitHub Desktop.
public static List<CompilerOutput> compile(String className, String code) {
try {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> ds = new DiagnosticCollector<>();
try (StandardJavaFileManager mgr = compiler.getStandardFileManager(ds, null, null)) {
JavaFileObject file = new InMemoryJavaCode(className, code);
Iterable<? extends JavaFileObject> sources = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, mgr, ds, null, null, sources);
task.call();
}
return ds.getDiagnostics().stream()
.map(InMemoryJavaCompiler::toCompilerOutput)
.collect(toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment