在Java中将String转换为运行时代码 [英] convert String to runtime code in java
问题描述
我正在创建一个可以逐行执行自定义代码的软件 因此,是否有任何方法函数或您想要执行的任何操作:
I'm creating a software that would execute custom code line by string SO, is there any method function or whatever you want that can do that :
String command="println("the TEST work !!!")";
magicExecMethod(command);
*它打印:测试工作!!!
*and it print : the TEST work !!!
谢谢
推荐答案
您有几种方法可以实现此目的.
You have several ways to achieve this.
您可以通过逐行打印来创建java
文件,然后通过从命令行调用编译器或调用java.lang.Compiler
进行编译,然后运行它.
You can create java
file by printing it line-by-line, then compile it by either invocation of compiler from command line or by calling java.lang.Compiler
, then run it.
其他方法是使用Groovy直接运行您的生产线-Groovy是支持Java语法并且可以在解释器模式下使用的基于Java的语言.
Other way is to run your line directly using Groovy - java based language that supports Java syntax and can be used in interpreter mode.
如果您不坚持使用Java语法,例如可以使用Java脚本,则可以使用ScriptingHost
和Rhino,这是自Java 1.5以来JDK的一部分.
If you are not sticky to java syntax and for example can use java script instead you can use ScriptingHost
and Rhino that is a part of JDK since java 1.5.
这篇关于在Java中将String转换为运行时代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!