编译java代码在另一个java代码中的字符串中可用

时间:2013-02-03 12:59:34

标签: java compiler-construction compilation java-compiler-api

  

可能重复:
  On-the-fly, in-memory java code compilation for Java 5 and Java 6
  Compiling Java file with code from within a Java file

我在一个程序的字符串中有一个hello world class,如下例所示,

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
  }  

}

有人可以帮助编译上面给出的示例中可用的内存字符串中的代码

2 个答案:

答案 0 :(得分:1)

您想查看javax.tools.JavaCompiler及相关课程。 该文档包含如何使用它们的示例。

请注意,只有安装了JDK才能使用java编译器。 JRE是不够的。

答案 1 :(得分:0)

另存为HelloWorld.java并执行以下操作:

  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");
    }

修改

可以看一下详细的例子:

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