Search code examples
javaeclipseclasspathjavacompilertools.jar

How to use JavaCompiler from tools.jar without JDK


I am trying to create an application that can compile a provided .java file during runtime. I understand that there is a programmatical compiler available within the tools.jar of the JDK. However, I cannot guarantee that the user of the application has JDK. I have attempted to package tools.jar within the application and reference it as a library. This seems to work within the Eclipse IDE when I have tools.jar added into the Bootstrap Entries of the classpath. When exporting the application to a runnable jar (with tools.jar packaged with it), ToolProvider.getSystemJavaCompiler(); returns null. I am not exactly sure what the issue is, but I believe it may have to do with the Bootstrap Entries of the classpath not being properly preserved when the application is exported to a runnable jar. Any ideas? Are there any alternatives to the tools.jar compiler that I could use? Thanks for your patience, as this is my first question posted here!


Solution

  • You need to use the compiler within "tools.jar"

    ToolProvider.getSystemJavaCompiler()
    

    will return the compiler from the jdk defined in the path variable, you can do this instead:

    File file = new File(pathToToolsJar);
    URL[] urls = new URL[]{ file.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(urls);
    Class compilerClass = loader.loadClass("com.sun.tools.javac.api.JavacTool");
    JavaCompiler compiler = (JavaCompiler) compilerClass.getConstructor().newInstance();
    

    Or you can add tools.jar as a library at compile time

    import com.sun.tools.javac.api.JavacTool;
    ...
    JavaCompiler compiler = new JavacTool();
    

    Or you can change System properties, but that leads to unexpected behaviors