Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

Save as HelloWorld.java and do 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

Can have a look at detailed example :

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top