Compiling java code available in string in other java code

Possible duplicate:
Compiling Java code in memory in Java for Java 5 and Java 6
Compiling a Java file with code from a Java file

I have a hello world class available in the program line 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 compile the code in the memory string available in the above example

+3


source to share


2 answers


You want to look at the javax.tools.JavaCompiler

related classes as well. The documentation contains examples of how to use them.



Please note that the java compiler will only work if you have the JDK installed. JRE is not enough.

+1


source


Save as HelloWorld.java and do the following:

  String fileToCompile = "HelloWorld.java";
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  int compilationResult = compiler.run(null, null, null, fileToCompile);
    if(compilationResult == 0){
        System.out.println("Compilation is successful");
    }else{
        System.out.println("Compilation Failed");
    }

      

Edit



You can take a look at a detailed example:

http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm

0


source







All Articles