从java程序中编译.java文件? [英] Compile .java file from within a java program?
问题描述
我发现这个代码:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler
if(compiler.run(null,null,null,fileName)!= 0){
System.err.println(Could not compile。
System.exit(0);
}
但是,这会返回NullPointerException
线程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)
我读到JRE不包括在Java程序中编译的能力, / p>
我不想要一个只在几台计算机上工作的程序,这些计算机必须手动设置JDK库而不是JRE的路径。考虑到这一点,这个问题有没有什么工作?
如果可能,我也希望跨平台工作。
没有解决方法,JRE不包含编译器,而JDK。如果你想使用Java编译器,那么你需要使用JDK来运行你的程序。
然而,在运行时还有其他方法来创建可执行的Java代码;有各种字节码汇编器 允许你不使用编译器动态构建你的代码。 ASM 是一个艰难的岩石; Apache BCEL 是另一种。
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.
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.
这篇关于从java程序中编译.java文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!