Skip to content

Commit 96b17fe

Browse files
committed
Added Support for CompileException to get notified when an error occures
1 parent 6d9d2cf commit 96b17fe

2 files changed

Lines changed: 31 additions & 6 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package org.mdkt.compiler;
2+
3+
/**
4+
* Created by PKeidel on 13.10.15.
5+
*/
6+
public class CompileException extends Exception {
7+
public CompileException(String msg) {
8+
super(msg);
9+
}
10+
}
Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,39 @@
11
package org.mdkt.compiler;
22

3-
import javax.tools.JavaCompiler;
4-
import javax.tools.JavaFileObject;
5-
import javax.tools.ToolProvider;
3+
import javax.tools.*;
4+
import java.io.IOException;
65
import java.util.Arrays;
6+
import java.util.Collections;
7+
import java.util.List;
78

89
/**
910
* Created by trung on 5/3/15.
11+
* Changed by PKeidel on 13.10.15.
1012
*/
1113
public class InMemoryJavaCompiler {
1214
static JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
1315

1416
public static Class<?> compile(String className, String sourceCodeInText) throws Exception {
17+
final DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
1518
SourceCode sourceCode = new SourceCode(className, sourceCodeInText);
1619
CompiledCode compiledCode = new CompiledCode(className);
17-
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceCode);
20+
Iterable<? extends JavaFileObject> compilationUnits = Collections.singletonList(sourceCode);
1821
DynamicClassLoader cl = new DynamicClassLoader(ClassLoader.getSystemClassLoader());
19-
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), compiledCode, cl);
20-
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, null, null, null, compilationUnits);
22+
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(diagnosticsCollector, null, null), compiledCode, cl);
23+
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, diagnosticsCollector, null, null, compilationUnits);
2124
boolean result = task.call();
25+
fileManager.close();
26+
27+
if (!result) {
28+
StringBuilder sb = new StringBuilder();
29+
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
30+
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
31+
// read error dertails from the diagnostic object
32+
sb.append("=> ").append(diagnostic.getMessage(null)).append("\n");
33+
}
34+
throw new CompileException(sb.toString());
35+
}
36+
2237
return cl.loadClass(className);
2338
}
2439
}

0 commit comments

Comments
 (0)