javacompilationjava-compiler-api

Compiling java Code Available In A String within another java code


Possible Duplicate:
On-the-fly, in-memory java code compilation for Java 5 and Java 6
Compiling Java file with code from within a Java file

i have a hello world class available in the string of a program as given in the example below,

public class CompileJavaString {   
  public static void main(String arg[]) {
     String s="public class HelloWorld{ public static void main(String arg[]) ";
     s=s+" { System.out.println(\"Hello World\"); }  } ";
     // this is the complete code of Hello World class taken as an example   

     // code to compile the class Hello World available in string and 
     // generate the HelloWorld.class file required here
  }  

}

can someone help to compile the code in a memory string available in example given above


Solution

  • You want to have a look at javax.tools.JavaCompiler and related classes. The documentation contains examples of how to use them.

    Note that the java compiler will only work if you have a JDK installed. A JRE is not enough.