21 Aug 2008 @ 12:09 AM 
 

Java compiler API, compiling made easy

 


1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.33 out of 5)
Loading ... Loading ...
2,645 views

Before Java 1.6 was released to the public I used the Runtime class (found in java.lang) to call the java compiler (javac.exe) directly to compile a Java file from another Java application, the line of code that i used looks like this

JAVA:
  1. Runtime.getRuntime().exec("C:\\WINDOWS\\system32\\cmd.exe /c start javac " +  userDir + "\\test\\"+className + ".java");

But luckily for me Java 1.6 introduced a handy utility that makes it possible to compile a Java application within a Java application without making direct calls to an external application. To demonstrate that I wrote a HelloWorld Java file and a CompilerConsoleDemo class that compiles the HelloWorld java file.

JAVA:
  1. public class HelloWorld {
  2. public static void main(String[] args){
  3. System.out.println("Hello World");
  4. }
  5. }

I wrote the Java code below to compile the above code like this

JAVA:
  1. /*--------------------------------------------------------------------------
  2. CompilerConsoleDemo class
  3. *****************
  4. By: HappyFace   http://www.engineeringserver.com - http://www.javaforums.net
  5. Contact:        info [@] engineeringserver.com
  6. Version:        20/August/2008
  7. Last updated:   20/August/2008
  8. *****************
  9. Note: a demo that uses the Compiler API from Java SE 1.6
  10. //----------------------------------------------------------------------*/
  11. import java.io.File;
  12. import java.io.FileNotFoundException;
  13. import java.io.FileOutputStream;
  14. import java.io.FileReader;
  15. import java.io.OutputStream;
  16. import java.util.Scanner;
  17.  
  18. import javax.tools.JavaCompiler;
  19. import javax.tools.ToolProvider;
  20.  
  21. public class CompilerConsoleDemo{
  22. static String userDir = System.getProperty("user.dir");
  23. String errOutput =userDir + "out.txt";
  24. Scanner sc;
  25. int lines = 1;
  26. String input = null;
  27.  
  28. public static void main(String[] args){
  29. CompilerConsoleDemo CD = new CompilerConsoleDemo(userDir + "\\HelloWorld.java");
  30. System.out.println("Compiling:");
  31. CD.showCode();
  32. System.out.println();
  33. System.out.println("Result(s):");
  34. CD.CompileCode();
  35. }
  36.  
  37. public CompilerConsoleDemo(String input){
  38. this.input = input;
  39. }
  40.  
  41. public void showCode(){
  42. String readCode;
  43. lines= 1;
  44. File f = new File(input);
  45. try {
  46. sc = new Scanner(f);
  47. while(sc.hasNext()){
  48. readCode = sc.nextLine();
  49. System.out.println(lines + " " + readCode);
  50. lines++;
  51. }
  52. } catch (FileNotFoundException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. public void CompileCode(){
  57. lines = 1;
  58. try {
  59. OutputStream err = new FileOutputStream(errOutput);
  60. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  61. int result = compiler.run(null,null,err,input);
  62.  
  63. if(result == 0){
  64. System.out.println("File successfully compiled!");
  65. System.out.println("");
  66. System.out.println("Output:");
  67. HelloWorld hw = ( HelloWorld ) Class.forName( "HelloWorld" ).newInstance();
  68. hw.main(null);
  69.  
  70. }
  71. else{
  72. f = new FileReader(errOutput);
  73. sc = new Scanner(f);
  74. String readErr;
  75. while(sc.hasNext()){
  76. readErr = sc.nextLine();
  77. System.out.println(lines + " " + readErr);
  78. lines++;
  79. }
  80. }
  81. } catch (FileNotFoundException e) {
  82. e.printStackTrace();
  83. // TODO Auto-generated catch block
  84. e.printStackTrace();
  85. // TODO Auto-generated catch block
  86. e.printStackTrace();
  87. // TODO Auto-generated catch block
  88. e.printStackTrace();
  89. }
  90. }
  91. }

The output should look like this
Compiling:
1 public class HelloWorld {
2 public static void main(String[] args){
3 System.out.println("Hello World");
4 }
5 }

Result(s):
File successfully compiled!

Output:
Hello World

But if an error occurred this will be shown instead
Compiling:
1 public class HelloWorld {
2 public static void main(String[] args){
3 System.out.println("Hello World")
4 }
5 }

Result(s):
1 C:\Eclipseworkspace\Demo\HelloWorld.java:3: ';' expected
2 System.out.println("Hello World")
3 ^
4 1 error

It looks like a really powerful utility but I haven't looked into the JavaCompiler class that much myself so there are still things that I need to figure out about the Compiler API to make maximal use it.

Related posts

Your Ad Here
Tags Tags: , , ,
Categories: Java
Posted By: HappyFace
Last Edit: 22 Nov 2008 @ 05 48 PM

EmailPermalink
 

Responses to this post » (One Total)

 
  1. [...] will once i have the time to write a readme and license for it. However you can take a look here: Engineeringserver.com | Java compiler API, compiling made easy and here Engineeringserver.com | [ java file copy ] Java folder watching to combine both of my [...]

Post a Comment

You must be logged in to post a comment.

\/ More Options ...
Change Theme...
  • Users » 888
  • Posts/Pages » 1,444
  • Comments » 506
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Online Users



    No Child Pages.

Forum



    No Child Pages.