Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Steven Avatar asked Dec 04 '12 06:12

Steven


1 Answers

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.

like image 126
Jon Skeet Avatar answered Sep 30 '22 06:09

Jon Skeet