How do I programmatically compile Java class?

Category: javax.tools, viewed: 6825 time(s).

This example using the Java Compiler API introduced in JDK 1.6 to programmatically compile a Java class. Here we'll compile the Hello.java. The process of compiling can be start by obtaining a JavaCompiler from the ToolProvider.getSystemJavaCompiler().

The simplest way to compile is by calling the run() method of the compiler and passing the first three arguments with null value. These three argument will use the default System.in, System.out and System.err. The final parameter is the file of the Java class to be compiled.

When error happened during compilation process the non-zero result code will be returned. After the compile process you'll have the Hello.class just as if you were compiling using the javac command.

package org.kodejava.example.tools;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompileHello {
    public static void main(String[] args) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(null, null, null,
                "src/org/kodejava/example/tools/Hello.java");

        System.out.println("Compile result code = " + result);
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats