ToolProvider.getSystemJavaCompiler() returns null

2019-01-25 02:49发布

I am trying to use the JavaCompiler class:

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.

标签: java javac
8条回答
一纸荒年 Trace。
2楼-- · 2019-01-25 03:20

On a Mac this worked for me:

  System.setProperty("java.home", "/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home");
  javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

(It does not work for idk 10 for some reason).

查看更多
Bombasti
3楼-- · 2019-01-25 03:23

Another solution is from: - http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7181951

Copy tools.jar in JDK_HOME/lib/ into JRE_HOME/lib/. At least to me, it solved my issue magically!

(I did nothing recommended as above. I just copied it there.)

查看更多
我只想做你的唯一
4楼-- · 2019-01-25 03:25

Just copy tools.jar file from /lib to It works

You can obtain by System.out.println( System.getProperty( "java.home"))

Most of time it is like C:\Program files\Java\jre(version) [ for windows ]

查看更多
女痞
5楼-- · 2019-01-25 03:25

I had both JRE and JDK in my buildPath...i just removed the JRE and it fixed.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-25 03:27

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

查看更多
ら.Afraid
7楼-- · 2019-01-25 03:32

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);
查看更多
登录 后发表回答