Java examples for javax.tools:JavaCompiler
compile Java code to target folder
import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.List; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class Main{ public static void main(String[] argv) throws Exception{ String sourceDir = "java2s.com"; String targetDir = "java2s.com"; System.out.println(compile(sourceDir,targetDir)); }// w w w . ja v a 2s .co m public static CompileResult compile(String sourceDir, String targetDir) throws Throwable { // sourceDir is blank if (isBlank(sourceDir)) { throw new IllegalArgumentException("sourceDir is blank"); } // targetDir is blank if (isBlank(targetDir)) { throw new IllegalArgumentException("targetDir is blank"); } /* * ? -d:??classes?? -cp:??classPath * -sourcepath:?? */ String classPath = SystemClassPathFinder.findSystemClassPath(); Iterable<String> options = null; if (isBlank(classPath)) { options = Arrays.asList("-d", targetDir, "-sourcepath", sourceDir); } else { options = Arrays.asList("-d", targetDir, "-sourcepath", sourceDir, "-cp", SystemClassPathFinder.findSystemClassPath()); } // classes FileOperateUtil.mkdirs(targetDir); // return compileFiles(sourceDir, options); } private static boolean isBlank(String abc) { return abc == null ? true : abc.trim().equals(""); } private static CompileResult compileFiles(String sourceDir, Iterable<String> options) throws IOException { List<File> sourceFiles = FileOperateUtil.findSourceFiles(sourceDir); // JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // StandardJavaFileManager fileManager = compiler .getStandardFileManager(null, null, null); // ? Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(sourceFiles); // DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); try { CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); // ? CompileResult compileResult = new CompileResult( compilationTask.call(), diagnostics); if (!compileResult.isCompileSuccess()) { System.err.println("compile error,sourceDir:" + sourceDir + " errorInfo:" + compileResult.toString()); } return compileResult; } finally { fileManager.close(); } } }