DynamicCompiler { public Class<?> compile(String name, CharSequence source, List<String> optionList) { Map<String, CharSequence> sources = new HashMap<String, CharSequence>(); sources.put(name, source); Map<String, Class<?>> compiledClasses = this.compileMany(sources, optionList); Class<?> clazz = compiledClasses.get(name); return clazz; } DynamicCompiler(ClassLoader classLoader, DiagnosticListener<JavaFileObject> diagnosticListener); Class<?> compile(String name, CharSequence source, List<String> optionList); Map<String, Class<?>> compileMany(Map<String, CharSequence> sources, List<String> optionList);  }
@Test public void testCompileOneClass() throws Exception { ClassLoader classLoader = this.getClass().getClassLoader(); DiagnositicsLogger diagnosticsLogger = new DiagnositicsLogger(); DynamicCompiler compiler = new DynamicCompiler(classLoader, diagnosticsLogger); String src = "package com.joliciel.talismane.utils.compiler.foo;\n" + "import com.joliciel.talismane.utils.compiler.DynamicCompilerTest.HelloInterface;\n" + "public class Foo implements HelloInterface {\n" + " public String hello(String who) {\n" + " return \"Hello \" + who;\n" + " }\n" + " }"; String fullName = "com.joliciel.talismane.utils.compiler.foo.Foo"; @SuppressWarnings("unchecked") Class<HelloInterface> helloClass = (Class<HelloInterface>) compiler.compile(fullName, src, null); HelloInterface foo = helloClass.newInstance(); assertEquals("Hello world", foo.hello("world")); }
@Test public void testCompileError() throws Exception { ClassLoader classLoader = this.getClass().getClassLoader(); DiagnositicsLogger diagnosticsLogger = new DiagnositicsLogger(); DynamicCompiler compiler = new DynamicCompiler(classLoader, diagnosticsLogger); String src = "package com.joliciel.talismane.utils.compiler.foo;\n" + "import com.joliciel.talismane.utils.compiler.DynamicCompilerTest.HelloInterface;\n" + "public class Foo implements HelloInterface {\n" + " public String hello(String who) {\n" + " return \"Hello \" + who\n" + " }\n" + " }"; String fullName = "com.joliciel.talismane.utils.compiler.foo.Foo"; try { compiler.compile(fullName, src, null); fail("Expected exception"); } catch (DynamicCompilerException e) { LOG.debug(e.getMessage()); } Diagnostic<? extends JavaFileObject> diagnostic = diagnosticsLogger.getDiagnostics().get(0); assertEquals(5, diagnostic.getLineNumber()); assertEquals("compiler.err.expected", diagnostic.getCode()); assertEquals("Foo.java", diagnostic.getSource().getName()); }