programmatically compiling a Java source file


/ Published in: Java
Save to your folder(s)

this simple snippet compiles a Java source file.


Copy this code and paste it in your HTML
  1. package ex.tajti.tools;
  2.  
  3. import javax.tools.Diagnostic;
  4. import javax.tools.DiagnosticListener;
  5. import javax.tools.JavaCompiler;
  6. import javax.tools.JavaFileObject;
  7. import javax.tools.StandardJavaFileManager;
  8. import javax.tools.ToolProvider;
  9.  
  10. /**
  11.  *
  12.  * @author ákos tajti
  13.  */
  14. public class Compiler {
  15.  
  16. /**
  17.   * compiles a java source file with the given <code>fileName</code>
  18.   *
  19.   * @param fileName
  20.   */
  21. public void compile(String fileName) {
  22. /*
  23.   * the compiler will send its messages to this listener
  24.   */
  25. DiagnosticListener listener = new DiagnosticListener() {
  26.  
  27. public void report(Diagnostic diagnostic) {
  28. System.err.println("gond: " + diagnostic.getMessage(null));
  29. System.err.println("sor: " + diagnostic.getLineNumber());
  30. System.err.println(diagnostic.getSource());
  31. }
  32. };
  33.  
  34. //getting the compiler object
  35. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  36. StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
  37. Iterable<? extends JavaFileObject> files = manager.getJavaFileObjects(fileName);
  38. JavaCompiler.CompilationTask task = compiler.getTask(null, manager, listener, null, null, files);
  39.  
  40. // the compilation occures here
  41. task.call();
  42. }
  43. }

URL: http://cesjava.freeblog.hu

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.