Compiling with javac from within Java

  • Follow


After decompiling many undocumented classes, I finally discovered
a way to invoke Javac from within the JVM without using exec, running
the compiler inside the same JVM. This is MUCH faster than using JavaC
if you want to do repeat compiles. This is how ANT does it.


// compiling from within a JVM
// without spawning javac.exe or a separate JVM
// com.sun.tools.javac.Main lives in tools.jar
// Make sure it is on the classpath. It won't be by default.
import com.sun.tools.javac.Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

// ...

// simulate an arbitrarily long command line. 
// No wildcards since no command line interpreter to expand them.
String[] optionsAndSources = { "-g", "-source", "1.5", "-target",
"1.5", "Apple.java", "Banana.java", "Cantaloup.java"};

// where Javac output goes
PrintWriter out = new PrintWriter( new FileWriter( "C:/temp/out.txt" )
);

// Compile all three sources at once
int status =  Main.compile( optionsAndSources, out );
System.out.println( "status: " + status );

For future reference, this is documented in the Java glossary under
javac.exe  at
http://mindprod.com/jgloss/javacexe.html
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
0
Reply my_email_is_posted_on_my_website (4730) 11/5/2005 4:37:32 PM

On Sat, 05 Nov 2005 16:37:32 GMT, Roedy Green wrote:
> After decompiling many undocumented classes, I finally discovered a
> way to invoke Javac from within the JVM without using exec, running
> the compiler inside the same JVM. This is MUCH faster than using
> JavaC if you want to do repeat compiles.

Congratulations. The technique is described by Sun in a TechTip from
July 2003:

  http://java.sun.com/developer/JDCTechTips/2003/tt0722.html

/gordon

-- 
[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e
0
Reply not108 (1060) 11/5/2005 3:54:38 PM


1 Replies
46 Views

(page loaded in 0.068 seconds)

Similiar Articles:













7/27/2012 6:34:03 PM


Reply: