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 72 73 74 75 76 77 78 79 80 81 82 83 84
| public static void compileJavaFromString() { StringBuilder sb = new StringBuilder(); String className = "Hello";
sb.append("public class Hello{\n"); sb.append("public static void main(String[]args){\n"); sb.append("System.out.print(\"hello world\"); \n"); sb.append("}\n"); sb.append("}");
Class<?> c = compile(className, sb.toString()); try { Object obj = c.newInstance(); Method m = c.getMethod("main", String[].class); m.invoke(obj, new Object[] { new String[] {} }); } catch (Exception e) { e.printStackTrace(); }
}
private static Class<?> compile(String className, String javaCodes) {
JavaSourceFromString srcObject = new JavaSourceFromString(className, javaCodes); System.out.println(srcObject.getCode()); Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(srcObject);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
String flag = "-d"; String outDir = ""; try { File classPath = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()); outDir = classPath.getAbsolutePath() + File.separator; System.out.println(outDir); } catch (URISyntaxException e1) { e1.printStackTrace(); } Iterable<String> options = Arrays.asList(flag, outDir);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, options, null, fileObjects);
boolean result = task.call(); if (result == true) { try { return Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { for (Diagnostic diagnostic : diagnosticCollector .getDiagnostics()) { System.out.println("Error on line: " + diagnostic.getLineNumber() + "; URI: " + diagnostic.getSource().toString()); } } return null; }
|