Java examples for javax.tools:JavaCompiler
compile Java Source
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class Main{ public static void main(String[] argv) throws Exception{ File javaFile = new File("Main.java"); String[] compilerOptions = new String[]{"1","abc","level",null,"java2s.com","asdf 123"}; System.out.println(compileJavaSource(javaFile,compilerOptions)); }/* ww w. j a v a2 s . c o m*/ /** * * * @param javaFile * @param compilerOptions * @return * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public static Class<?> compileJavaSource(File javaFile, String[] compilerOptions) throws IOException, ClassNotFoundException { File parentFile = null; JavaCompiler javaCompiler = null; StandardJavaFileManager fileManager = null; Iterable<? extends JavaFileObject> fileObjects = null; JavaNameScanner nameScanner = null; URL[] urls = null; URLClassLoader urlClassLoader = null; Class<?> clazz = null; // Parent directory for Java source file parentFile = javaFile.getParentFile(); // Java compiler object javaCompiler = ToolProvider.getSystemJavaCompiler(); // Standard Java file manager object fileManager = javaCompiler.getStandardFileManager(null, null, null); // fileObjects = fileManager.getJavaFileObjects(javaFile); // Start reading Java source file for finding package name as // thread nameScanner = new JavaNameScanner(javaFile); new Thread(nameScanner).start(); // Compiler options List<String> opt = null; opt = new LinkedList<String>(); for (String s : compilerOptions) { opt.add(s); } opt.add("-d"); opt.add(javaFile.getParent()); // Start compilation (thread) javaCompiler.getTask(null, fileManager, null, opt, null, fileObjects).call(); // Close file manager fileManager.close(); // Load generated class via URLClassLoader urls = new URL[] { parentFile.toURI().toURL() }; urlClassLoader = new URLClassLoader(urls); // Wait for thread to complete synchronized (nameScanner) { try { while (nameScanner.getPackageName() == null && nameScanner.getClassName() == null) { nameScanner.wait(); } clazz = urlClassLoader.loadClass(nameScanner .getPackageName() + "." + nameScanner.getClassName()); } catch (InterruptedException ex) { ex.printStackTrace(); } } javaFile.delete(); return clazz; } }