Java - 将字符串作为普通代码运行 [英] Java - Run a string as normal code
问题描述
有没有办法将字符串作为代码运行?我的意思是,如果我运行了一个具有值 System.out.println("Hello World)
的字符串,我是否可以将字符串作为普通代码运行,然后输出将是 Hello World?
Is there a way to run a string as code? I mean if I had a string run having value System.out.println("Hello World)
could I run the string as normal code the then output will be Hello World?
例如:
String code = "System.out.println("Hello World)";
code.run(); //I know this doesn't work
控制台:
Hello World
推荐答案
你想要相当于 JavaScript 的 eval
.Java 中没有等价物.
You want the equivalent of JavaScript's eval
. There is no equivalent in Java.
嗯,有,但这不是微不足道的.
Well, there is but it's not trivial.
您可以生成包含该代码的类的完整源代码.类似的东西
You can generate the full source code of a class containing that code. Something like
public class StuffToDynamicallyCompile {
public static final void main(String[] ignored) {
PUT STUFF HERE!
}
}
然后以编程方式调用编译器,如此答案中所述,或如评论中所述:如何从java程序中编译.java文件
And then programatically invoke the compiler, as described in this answer, or as stated in the comments: How to compile .java file from within java program
不是一个简单的任务.也许有一种方法可以最大限度地减少您的要求,因此您可以允许一组极其有限的命令,只需使用开关执行它(如果 'dothis' 然后调用 doThis()
, else if 'doThat',调用 doThat()
等).
Not a simple task. Perhaps there's a way to minimize your requirements, so you can allow an extremely limited set of commands, and just execute it with a switch ("if 'dothis' then call doThis()
, else if 'doThat', call doThat()
, etc.).
这篇关于Java - 将字符串作为普通代码运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!