在 Java 中是否有等效于 Python 的 exec() 函数?

Is there an equivalent to Python's exec() function in Java?

在python中,可以使用exec()执行一段代码

在 Java 中有什么方法可以做到这一点,这样我就可以从字符串中调用函数,还可以做其他事情,比如获取一些用户输入并 运行 它作为 Java 代码。

注意:这与Is there an eval() function in Java?不同;那只会 eval() 我想要 exec().

你有几个选择

1)动态编译加载一个java类

How do you dynamically compile and load external java classes?

就像 Peter Lawrey 建议的那样 net.openhft.compiler 你可以做你想做的事

https://github.com/OpenHFT/Java-Runtime-Compiler

// dynamically you can call
String className = "mypackage.MyClass";
String javaCode = "package mypackage;\n" +
                 "public class MyClass implements Runnable {\n" +
                 "    public void run() {\n" +
                 "System.out.println(\"Hello World\");\n" +
                 "     }\n" +
                 "}\n";
Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
Runnable runner = (Runnable) aClass.newInstance();
runner.run();

我测试了这个解决方案,它工作得很好。

观察:你需要在你的项目中添加依赖 ${env.JAVA_HOME}/lib/tools.jar

2) 在您的 Java 中使用另一种语言来解释您的代码,例如使用 Jython:

String arbitraryPythonCode = "";
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(arbitraryPythonCode);

您还可以使用 Javascript、Groovy、Scala 等