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

爱⌒轻易说出口 提交于 2019-11-28 10:44:56

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");

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);
PSR

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

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 ]

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.)

here is simple solution that worked for me

I just changed the jre System library to .....Program Files\Java\jdk1.7.0_55\jre instead of ....Program Files\Java\jdk1.7.0_55\bin and it worked for me.

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).

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!