File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Compile at runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Compile at runtime" Watch "Compile at runtime" New topic

Compile at runtime

Mike Broadbear
Ranch Hand

Joined: Jan 14, 2002
Posts: 39
Is there a way to compile a .java source file at runtime?
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Mike,
Yep, checkout java.lang.Runtime. It has all of the old Unix style exec() functions. For example:

Hope this helps,
Michael Morris

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Deos anybody know if such commands work on Macs?

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
From Apples - The Care and Feeding of Runtime.exec.

For example, you can invoke the Java compiler thusly:
String args = {"java", "", ...javac argument list...};

"JavaRanch, where the deer and the Certified play" - David O'Meara
john guthrie
Ranch Hand

Joined: Aug 05, 2002
Posts: 124
You don't need to Runtime.exec the compiler. I know ant doesn't do this...
Looking at the ant source code, it looks like they use a class names "", so if you can find that (again, the ant src distro would help here), you can do it
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi John,
That is a good point. Most of us tend to forget about the propriatery packages that are available to us since there is usually not a published API nor any guarantee that they will remain as is. But I'm sure your method would work fine.
Michael Morris
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
Check Rodey Green's Java Glossary entry on javac - under the table of command line switches he gives a usage example.
This class is in JAVA_HOME/lib/tools.jar, so you have to include that in CLASSPATH to use it from a program.
As I recall, the main() method is used from javac.exe, but it does a System.exit() - so you don't want to do that from your program. Use the compile() method which returns a boolean for success/fail.
I agree. Here's the link:
subject: Compile at runtime
It's not a secret anymore!