简体   繁体   中英

Compile .java file from within a java program?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM