9

I have a scenario where I have to generate Java code when my application is running.

Can compile and run than code from my application( as a separate application).

Is it possible to compile and then use it from the same application. Cant think of any possibility

Tasawer Khan
  • 5,994
  • 7
  • 46
  • 69

3 Answers3

11

Check out Create dynamic applications with javax.tools. Second time I've referenced this today--I swear I don't work for them.

karmakaze
  • 34,689
  • 1
  • 30
  • 32
5

You can use an instance of JavaCompiler:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

Follow the link for the an example on how to use it.

iruediger
  • 933
  • 6
  • 9
  • 2
    Note that you will need a JDK for this to work. The JRE install does not include a compiler. – Thorbjørn Ravn Andersen May 18 '11 at 23:26
  • Good point Thorbjørn. If he chooses this alternative, the minimum requirement for his application will be **JDK 6**. – iruediger May 18 '11 at 23:35
  • JRE 7 appears to have put javax.tools.ToolProvider right in the rt.jar. Although I haven't tested this out, I do see in `jdk1.7.0_05/jre/lib/rt.jar`: `javax/tools/JavaCompiler.class` and `javax/tools/ToolProvider.class` – karmakaze Jul 20 '12 at 02:18
1

using the ProcessBuilder or Runtime.exec() you can run any commandline app from your java code

this includes the javac compiler and java as a separate process

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • When running MyCompilingUtility.java, which calls`Runtime#exec()` with a parameter of `javac MyFile.java` where `MyFile.java` was created via `PrintWriter` by `MyCompilingUtility.java`, I don't see a `class` file generated for `MyFile.java`. Why's that? – Kevin Meredith Feb 05 '14 at 15:08
  • 1
    check the error output of javac, javac expects the working directory to be the root package of the class it is compiling – ratchet freak Feb 05 '14 at 16:37
  • Thanks, @ratchet freak. Posting Sotirios Delimanolis's comment to elaborate on your helpful suggestion - http://stackoverflow.com/questions/21580975/using-runtimeexec-with-javac-no-class-file/21581168?noredirect=1#comment32600305_21581168 – Kevin Meredith Feb 05 '14 at 16:57