在Java中是否有等效于Python的exec()函数? [英] Is there an equivalent to Python's exec() function in Java?
问题描述
在python中,您可以使用 exec()
执行一段代码.
In python, you can use exec()
to execute a piece of code.
在Java中有没有办法做到这一点,所以我可以从字符串中调用函数,还可以做其他事情,例如获取一些用户输入并将其作为Java代码运行.
Is there's any way to do this in Java, so that I can call a function from a string, but also do other things as-well like getting some user input and running it as Java code.
注意:这与中是否存在eval()函数不同在Java中?;那只做 eval()
,而我要 exec()
.
Note: This is not the same as Is there an eval() function in Java?; That only does eval()
and I want exec()
.
推荐答案
您有几个选择
1)动态编译并加载Java类
1) Dynamically compile and load a java classes
就像彼得·劳里(Peter Lawrey)建议使用net.openhft.compiler,您可以做自己想做的事
Like Peter Lawrey suggests using net.openhft.compiler you can do what you want
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();
我测试了此解决方案,并且效果很好.
I tested this solution and it work perfectly.
观察:您需要添加项目的依赖项$ {env.JAVA_HOME}/lib/tools.jar
Observation: You need to add in the dependencies of your project ${env.JAVA_HOME}/lib/tools.jar
2)在Java内部使用另一种语言来解释代码,例如Jython:
2) Use another language inside of your Java that interpret your code, example with Jython:
String arbitraryPythonCode = "";
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(arbitraryPythonCode);
您还可以使用Javascript,Groovy,Scala等
You can also use Javascript, Groovy, Scala, etc.
这篇关于在Java中是否有等效于Python的exec()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!