Call Java compiler programatically

You don’t need to add any dependency

	private static void doCompile(File sourceDir) throws SomeException {
		System.out.println("Compiling started");
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector diagnostics = new DiagnosticCollector();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
		Collection files = FileUtils.listFiles(sourceDir, new String[] { "java" }, true);		 
		Iterable compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
		List compilerOptions = Arrays.asList("-source", "1.6", "-target", "1.6");
		JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, compilerOptions, null, compilationUnits);
		boolean success = task.call();
		try {
			fileManager.close();
		} catch (IOException e) {
			// ignore it
		}
		if (!success) {
			StringBuffer errors = new StringBuffer();
			for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
				errors.append(String.format("Compilation Error on line %d in %s", diagnostic.getLineNumber(), diagnostic)).append("\n");
			}
			throw new SomeException(errors.toString());
		}
	}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.