Sunday, June 26, 2011

programmatically compiling a Java source file..!

  /**
     * compiles a java source file with the given <code>fileName</code>
     *
     * @param fileName
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    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();
    }

No comments:

Post a Comment