Compilation

The JavaCompiler is quite simple. You have to provide the paths to the sources, where to get the sources from and where to store the classes. Then you just pick one of the compilers to do the work. The result of the compilation is returned as a CompilationResult.

JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir), new FileResourceStore(targetDir));

System.out.println( result.getErrors().length + " errors");
System.out.println( result.getWarnings().length + " warnings");

Information like line numbers of errors etc are accessible in a consistent way. If supported by the compiler you can even get notified about error before the end of the compilation. (see the CompilationProblemHandler) for that. The example module provides a simple JSP servlet and a javac-like command line interface.

Filesystem monitoring

A subproject of JCI provides a FilesystemAlterationMonitor that can be used to get notified when files change on the local filesystem. If you attach a ReloadingListener or a CompilingListener it can even trigger the reload of a class in the ReloadingClassLoader.

ReloadingClassLoader classloader = new ReloadingClassLoader(this.getClass().getClassLoader());
ReloadingListener listener = new ReloadingListener();

listener.addReloadNotificationListener(classloader);

FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
fam.addListener(directory, listener);
fam.start();

But you can also just implement a simple FilesystemAlterationListener yourself and just use it to get notified about configuration files changes for example. The example just extends the FileChangeListener that provides a few convenience methods.

Maven artifacts

Commons JCI is split into several modules, there is one artifact per compiler. Using the Eclipse compiler requires to declare the following dependency in your project:

  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-jci-eclipse</artifactId>
      <version>1.1</version>
  </dependency>

The other artifacts are commons-jci-groovy, commons-jci-janino and commons-jci-rhino.