Compile Java Files At Runtime

Java 6 has a new Compiler API, as a result of JSR 199, which requests for a standard way to compile java source files. Although I use a lot of Java, I don't get to use some of the Java API's, as they are not required for the business functionality that I usually code. So, I was looking around for some new ideas or code to try and thought of working on a simple Java IDE and got to work on JavaCompiler class from package of Java 6. Here's a naive example, that shows how to compile a Java source file at runtime:


  1. Nice article. I had seen Java 6 new Compiler API but never tried it before. Never thought it will be that simple to compile Java program at runtime.

  2. This comment has been removed by the author.

  3. While running the above code. I faced the NPE Exception on
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    that was because my classpath was pointing to JRE lib instead of JDK. tools.jar which contains compiler was not the classpath.more details are here.


Note: Only a member of this blog may post a comment.