3

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

2
  • 2
    Write the the string to HelloWorld.java and call javac? Commented Feb 3, 2013 at 13:01
  • 2
    Here is the code Commented Feb 3, 2013 at 13:06

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

i don't want to save it to .java file, this is the real task i have to do because i have to save the time consumed while writing to .java file and reading again.
it is giving an exception. NullPointerException

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.