返回顶部

收藏

在程序中编译 Java 源码

更多

Compiler.java

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();
    }
}

标签:编译,DiagnosticListener,JavaCompiler,StandardJavaFil

收藏

0人收藏

支持

0

反对

0