Compile .java file from within a java program?

不打扰是莪最后的温柔 提交于 2019-12-24 02:14:44

问题


I found this code:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

if(compiler.run(null, null, null, fileName) != 0) {
    System.err.println("Could not compile.");
    System.exit(0);
}

However, this returns a NullPointerException

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at net.foxycorndog.foxy.compiler.Compiler.compile(Compiler.java:25)
at net.foxycorndog.foxy.compiler.Parser.parse(Parser.java:41)
at net.foxycorndog.foxy.Foxy$ActionHandler.actionPerformed(Foxy.java:99)

I read that the JRE does not include the ability to compile within a java program, but the JDK does.

I don't want a program that only works on a few computers that have had to manually set the path to the JDK library instead of JRE. With this in mind, is there any work around for this problem?

I would also like it to work over cross platform if possible.


回答1:


There's no workaround to the fact that the JRE doesn't contain a compiler, and the JDK does. If you want to use the Java compiler, then you'll need to run your program with the JDK.

There are other ways to create executable Java code at runtime, however; there are various bytecode assemblers that let you build your code dynamically without use of a compiler. ASM is one that rocks hard; the Apache BCEL is another.



来源:https://stackoverflow.com/questions/10158423/compile-java-file-from-within-a-java-program

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