Skip to content

How to set classpath when I use compile the source?

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


The method takes an options parameter that allows to set compiler options. The following message describes an easy way to set them in order to access the calling program’s classpath:

You need to configure the standard java file manager to know about the jar files(s) – you use the compiler options argument to do that.

By default the java compiler object only seems to know about the default locations for bootclasspath, extdirs and endorseddirs directories in terms of its classpath.

You need to add the calling program’s current classpath to the java compiler instance’s which gets passed on the the standard file manager, which will then find classes in the jar files.

Here’s how I do it in the compiler wrapper I wrote

List<String> optionList = new ArrayList<String>();
// set compiler's classpath to be same as the runtime's

// any other options you want

JavaCompiler.CompilationTask task = compiler.getTask(out,jfm,diagnostics,optionList,null,jfos);

All you’ll need then is to get the proper classpath set when running the calling program.