How to set classpath when I use javax.tools.JavaCompiler compile the source?

Viewed 19659

I use the class javax.tools.JavaCompiler (jdk6) to compile a source file, but the source file depends on some jar file. How to set the classpath of the javax.tools.JavaCompiler?

3 Answers

I needed something simpler than the examples above.

The following is a self-contained example of using the built-in Java compiler, and setting the classpath for the compiler to use.

It is equivalent to creating a source file called HelloPrinter.java and then compiling it as follows:

javac -classpath C:\Users\dab\Testing\a.jar;c:\path\etc org\abc\another\HelloPrinter.java

Note how the classpath can be set using a String[] of options. This should be familiar if you're already used to running javac on the command line (as above).

This code is compatible with Java 6. You will need a JDK, not a JRE, for this to run. This example doesn't actually use the classpath. It all does is print "Hello". You can add an import statement to the generated source and call a method in an external Jar file to test this properly.

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JavaCompilerExample {
    
    public static void main(String[] args) throws Exception {

        String className = "HelloPrinter";
        String directoryName = "org/abc/another";
        new File(directoryName).mkdirs();

        FileOutputStream fos = new FileOutputStream(directoryName+"/"+className+".java");
        PrintStream ps = new PrintStream(fos);
        ps.println(
                "package "+directoryName.replace("/", ".")  + " ; "
                + "public class " +className + 
                "{ public static void main(String[] args){System.out.println(\"Hello\");} }");
        ps.close();
        
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        String javacOpts[] = {"-classpath", 
                             "C:\\Users\\dab\\Testing\\a.jar;c:\\path\\etc;",
                              directoryName+"/"+className + ".java"};
        
        if ( javac.run(null, null, null,  javacOpts)!=0 ) {
            System.err.println("Error");
            System.exit(1);
        }
        
        
    }

}
Related