Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToolProvider.getSystemJavaCompiler() returns null - usable with only JRE installed?

Tags:

java

javac

I am trying to use the JavaCompiler class:

  • http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html

When I call ToolProvider.getSystemJavaCompiler() it returns null.

I think this is because I'm using a JRE instead of a JDK.

The problem is I want it to run on all platforms regardless of weather the user is using a JRE or a JDK.

If anyone knows how to fix this, or an alternative method to use please comment.

Any help would be appreciated.

like image 435
Josh Sobel Avatar asked Mar 20 '13 00:03

Josh Sobel


3 Answers

ToolProvider.getSystemJavaCompiler() is not available.

Is tools.jar missing from the classpath?

Set class path to the tools.jar file which can found in jdk\jre directory.

System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_02");

like image 52
Akhilesh Dhar Dubey Avatar answered Nov 10 '22 07:11

Akhilesh Dhar Dubey


Here is how to run the Java compiler from your application when there is no JDK installed.

First, include the tools.jar file from a JDK with your Java app and put tools.jar in your classpath. Oracle probably won't like you doing that. But, there is legal work-around. You get the tools.jar file from the free JDKs offered by openjdk.org (openjdk), RedHat (IcedTea), or Azul Systems (Zulu).

Next, instead of using ToolProvider.getSystemJavaCompiler() and the JavaCompiler class, call the compiler located in tools.jar directly. Below is snippet of code:

String classpath = ...; // make sure tools.jar is in this path 
String sourcepath = ...; // path to your sources
String putputpath = ...; // directory for generated class files
String filepath = ...; // file path the file you want to compile

String[] args = new String[] {
"-classpath", classpath,
"-sourcepath", sourcepath,
"-d", putputpath,
filePath
};
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
int compileStatus = javac.compile(args);
like image 40
George Van Treeck Avatar answered Nov 10 '22 07:11

George Van Treeck


I think this is the problem .Explicitly specifying the version of java.exe you're using as the one in your JDK directory.

see here for details

like image 34
PSR Avatar answered Nov 10 '22 06:11

PSR