Java examples for javax.tools:JavaCompiler
Java compiler
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; 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{ private static LogUtil log = LogUtil.getLogger(CompilerUtil.class); //w w w . j a va2 s . c o m private static boolean compiler(String encoding, String jars, String filePath, String distDir, DiagnosticCollector<JavaFileObject> diagnostics) { // ? JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler .getStandardFileManager(null, null, null); // filePathjava File sourceFile = new File(filePath); List<File> sourceFileList = new ArrayList<File>(); sourceFileList = getSourceFiles(sourceFile); // java? if (sourceFileList.size() == 0) { log.error(filePath + "java"); return false; } // ? Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(sourceFileList); //javajavajavaclass? -classpathclass Iterable<String> options = Arrays.asList("-encoding", encoding, "-classpath", jars, "-d", distDir); CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); // ? boolean res = compilationTask.call(); try { fileManager.close(); } catch (IOException e) { log.error("?"); log.error(e.getMessage()); } return res; } private static List<File> getSourceFiles(File sourceFile) { List<File> sourceFileList = new ArrayList<File>(); if (sourceFile.exists() && sourceFileList != null) {// if (sourceFile.isDirectory()) {// ?file? // ?.java? List<String> sourceFileListTmp = FileUtil .getFilesFromFolder(sourceFile.getPath(), "java"); for (String filePath : sourceFileListTmp) { sourceFileList.add(new File(filePath)); } } else {// ?file? sourceFileList.add(sourceFile); } } else { log.error("?: " + sourceFile); } return sourceFileList; } }