Steven
Steven

Reputation: 1809

Use of javax.tools to compile java source at Runtime?

So, java has a built in library dedicated for compiling java source code into .class files, and it is in javax.tools. So, I was wondering how exactly you get it to work. I've read through the javadoc, and it gives some examples in there, but when I use those examples, I get errors.

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

That is the example oracle gives in order to get an instance of the StandardJavaFileManager class from which you can do much more. However, I'm having some issues with the very first line of that code. When I attempt to do ToolProvider.getSystemJavaCompiler();, it always returns null. In the javadocs for that method, it says, "returns the compiler provided with this platform or null if no compiler is provided." But they never show any other way of getting an instance of a JavaCompiler. I've tried many other ways, such as using a ServiceLoader to find any reference of it that I could, but to no prevail. How might I go about getting this to work?

Upvotes: 5

Views: 1450

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 42005

The compilation is often performed by directly invoking the javac compiler, which requires an installed Java Development Kit (JDK) or by calling com.sun.tools.javac.Main, which can be found in Sun's tools.jar. Sun's licensing allows tools.jar to be redistributed with the full Java Runtime Environment (JRE). Other ways to implement such dynamic capabilities include using an existing dynamic scripting language (such as JavaScript or Groovy) that integrates with the application's implementation language (see Resources) or writing a domain-specific language and associated language interpreter or compiler.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503439

Chances are you're running Java from a JRE directory instead of a JDK directory - you need to run a version which "knows" where the Java compiler is.

So for example, on my Windows boxing, running a tiny test app like this:

import javax.tools.*;

class Test {
    public static void main(String[] args) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        System.out.println(compiler);
    }
}

The results are:

c:\Users\Jon\Test>"\Program Files\Java\jdk1.7.0_09"\bin\java Test
com.sun.tools.javac.api.JavacTool@1e0f2f6

c:\Users\Jon\Test>"\Program Files\Java\jre7\bin\java" Test
null

As you can see, it's fine when I specifically run the JDK version, but I get null when running the JRE version. Check how you're starting Java.

Upvotes: 9

Related Questions