Posted By

akostajti on 12/01/09


Tagged

java


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

adkatrit
kubaitis


programmatically compiling a Java source file


 / Published in: Java
 

URL: http://cesjava.freeblog.hu

this simple snippet compiles a Java source file.

  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. }

Report this snippet  

You need to login to post a comment.