-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathInMemoryJavaCompiler.java
More file actions
71 lines (53 loc) · 2.5 KB
/
InMemoryJavaCompiler.java
File metadata and controls
71 lines (53 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package org.mdkt.compiler;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import java.util.*;
/**
* Created by trung on 5/3/15.
*/
public class InMemoryJavaCompiler {
private static final Iterable<String> options = Collections.singletonList("-Xlint:unchecked");
private static JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DynamicClassLoader classLoader = new DynamicClassLoader(ClassLoader.getSystemClassLoader());
private DiagnosticCollector<JavaFileObject> collector;
public InMemoryJavaCompiler() {
this.collector = new DiagnosticCollector<>();
}
Map<String, SourceCode> clazzCode = new HashMap<>();
public void addSource(String className, String sourceCodeInText)
throws Exception {
clazzCode.put(className, new SourceCode(className, sourceCodeInText));
}
public Map<String, Class<?>> compileAll() throws Exception {
Collection<SourceCode> compilationUnits = clazzCode.values();
List<CompiledCode> compiledCodes = new ArrayList<>();
Iterator<SourceCode> iterator = compilationUnits.iterator();
for (SourceCode sourceCode : compilationUnits) {
compiledCodes.add(new CompiledCode(sourceCode.getClassName()));
}
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), compiledCodes, classLoader);
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, collector,
options, null, compilationUnits);
try {
boolean result = task.call();
if (!result || collector.getDiagnostics().size() > 0) {
throw new InMemoryCompilerException(collector.getDiagnostics());
}
Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
for (String className : clazzCode.keySet()) {
classes.put(className, classLoader.loadClass(className));
}
return classes;
} catch (ClassFormatError e) {
throw new InMemoryCompilerException(collector.getDiagnostics());
}
}
public Class<?> compile(String className, String sourceCodeInText) throws Exception {
addSource(className, sourceCodeInText);
Map<String, Class<?>> compiled = compileAll();
Class<?> compiledClass = compiled.get(className);
return compiledClass;
}
}