|
1 | 1 | package org.mdkt.compiler; |
2 | 2 |
|
3 | | -import javax.tools.JavaCompiler; |
4 | | -import javax.tools.JavaFileObject; |
5 | | -import javax.tools.ToolProvider; |
| 3 | +import javax.tools.*; |
| 4 | +import java.io.IOException; |
6 | 5 | import java.util.Arrays; |
| 6 | +import java.util.Collections; |
| 7 | +import java.util.List; |
7 | 8 |
|
8 | 9 | /** |
9 | 10 | * Created by trung on 5/3/15. |
| 11 | + * Changed by PKeidel on 13.10.15. |
10 | 12 | */ |
11 | 13 | public class InMemoryJavaCompiler { |
12 | 14 | static JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); |
13 | 15 |
|
14 | 16 | public static Class<?> compile(String className, String sourceCodeInText) throws Exception { |
| 17 | + final DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>(); |
15 | 18 | SourceCode sourceCode = new SourceCode(className, sourceCodeInText); |
16 | 19 | CompiledCode compiledCode = new CompiledCode(className); |
17 | | - Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceCode); |
| 20 | + Iterable<? extends JavaFileObject> compilationUnits = Collections.singletonList(sourceCode); |
18 | 21 | 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); |
21 | 24 | 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 | + |
22 | 37 | return cl.loadClass(className); |
23 | 38 | } |
24 | 39 | } |
0 commit comments