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

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

The link in this answer is broken now.
That's too bad, maybe this other Q/A will be useful.
5

You can use an instance of JavaCompiler:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

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

3 Comments

Note that you will need a JDK for this to work. The JRE install does not include a compiler.
Good point Thorbjørn. If he chooses this alternative, the minimum requirement for his application will be JDK 6.
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
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

3 Comments

When running MyCompilingUtility.java, which callsRuntime#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?
check the error output of javac, javac expects the working directory to be the root package of the class it is compiling
Thanks, @ratchet freak. Posting Sotirios Delimanolis's comment to elaborate on your helpful suggestion - stackoverflow.com/questions/21580975/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.