import javax.tools.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; /** * Created by nanashi07 on 15/12/13. */ public class CompileOnFly { public static void main(String args[]) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); out.println("package com.prhythm.output;"); out.println(); out.println("public class OutputImpl implements IOutput {"); out.println(); out.println(" public void printFor(String message) {"); out.println(" System.out.printf(\"Print from %s : %s%n\", getClass().getName(), message);"); out.println(" }"); out.println(); out.println("}"); out.close(); JavaFileObject file = new TextJavaObject("com.prhythm.output.OutputImpl", writer.toString()); Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file); JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits); boolean success = task.call(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { System.out.printf("Code: %s%n", diagnostic.getCode()); System.out.printf("Kind: %s%n", diagnostic.getKind()); System.out.printf("Position: %s%n", diagnostic.getPosition()); System.out.printf("StartPosition: %s%n", diagnostic.getStartPosition()); System.out.printf("EndPosition: %s%n", diagnostic.getEndPosition()); System.out.printf("Source: %s%n", diagnostic.getSource()); System.out.printf("Message: %s%n", diagnostic.getMessage(null)); } if (success) { try { URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File("").toURI().toURL()}); Class<?> outClass = Class.forName("com.prhythm.output.OutputImpl", true, classLoader); Object outInstance = outClass.newInstance(); outClass.getDeclaredMethod("printFor", new Class[]{String.class}).invoke(outInstance, "Bruce"); } catch (ClassNotFoundException e) { System.err.println("Class not found: " + e); } catch (NoSuchMethodException e) { System.err.println("No such method: " + e); } catch (IllegalAccessException e) { System.err.println("Illegal access: " + e); } catch (InvocationTargetException e) { System.err.println("Invocation target: " + e); } catch (InstantiationException e) { System.err.println("Initialize instance: " + e); } } } } class TextJavaObject extends SimpleJavaFileObject { final String code; TextJavaObject(String name, String code) { super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } }
Output:
Print from com.prhythm.output.OutputImpl : Bruce