用Java执行Java代码 [英] Execute Java code in Java
问题描述
可能重复:
将字符串转换为Java代码
Java上的动态代码执行
我有一个字符串包含:
for(int i = 0; i< 5; i ++){System.out.println(\* \);}
我可以用Java执行此String中的代码吗?
I have a String containing : "for(int i=0 ; i<5 ; i++){System.out.println(\"*\");}"
Can I execute the code in this String in Java?
推荐答案
从Java 6开始,你可以使用SDK中的标准API编译并运行定义为String或File的Java 编译单元(编译单元基本上是.java文件中的所有内容 - 包,导入, classes / interfaces / enumerations),看看这个示例 。但不能运行一个像您问题中那样的任意Java代码段。
Since Java 6, you can compile and run a Java compilation unit defined as a String or a File using standard APIs in the SDK (a compilation unit is basically everything that goes inside a .java file - package, imports, classes/interfaces/enumerations), take a look at this example. You can't run an arbitrary Java snippet like the one in your question, though.
如果可能的话,那就是一个更好的想法是嵌入一种不同的脚本语言,允许您从Java程序运行代码片段 - 例如,JavaScript,Groovy, MVEL , BeanShell 等。
If at all possible, it'd be a better idea to embed a different scripting language that allows you to run snippets of code from a Java program - for example, JavaScript, Groovy, MVEL, BeanShell, etc.
这篇关于用Java执行Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!