- package ex.tajti.tools;
- import javax.tools.Diagnostic;
- import javax.tools.DiagnosticListener;
- import javax.tools.JavaCompiler;
- import javax.tools.JavaFileObject;
- import javax.tools.StandardJavaFileManager;
- import javax.tools.ToolProvider;
- /**
- *
- * @author ákos tajti
- */
- public class Compiler {
- /**
- * compiles a java source file with the given <code>fileName</code>
- *
- * @param fileName
- */
- public void compile(String fileName) {
- /*
- * the compiler will send its messages to this listener
- */
- DiagnosticListener listener = new DiagnosticListener() {
- public void report(Diagnostic diagnostic) {
- System.err.println("gond: " + diagnostic.getMessage(null));
- System.err.println("sor: " + diagnostic.getLineNumber());
- System.err.println(diagnostic.getSource());
- }
- };
- //getting the compiler object
- JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
- StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
- Iterable<? extends JavaFileObject> files = manager.getJavaFileObjects(fileName);
- JavaCompiler.CompilationTask task = compiler.getTask(null, manager, listener, null, null, files);
- // the compilation occures here
- task.call();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/220220132191.html
来源: http://www.codesnippet.cn/detail/220220132191.html