执行存储在数据库中的Java代码 [英] Execute Java code that is stored in the database
问题描述
我有定期推送到数据库的Java代码(它太复杂,无法解释为什么它在数据库中,这只会把焦点从主要问题转移)。
I have Java code that is regularly pushed to the database (it is too complicated to explain why it is in the database, and that would just turn the focus away from the main question).
在运行时我查询数据库。我可以执行从数据库获取的代码吗?我只是将主要方法的内容存储在代码中。数据库运行的服务器是HTTP服务器。
During runtime I query the database. Can I execute the code I get from the database? I am only storing the content of the main method in the code. The server on which the database runs is an HTTP server.
数据库中的示例代码(仅供参考):
Example code from the database (just for reference):
int i = 10;
int j = 2;
int k = i*j;
System.out.println("Result is " + k);
预期输出:
Result is 20
推荐答案
程序是否正确Groovy程序。因此,您可以向您的项目添加Groovy依赖项,然后使用 GroovyShell 执行代码:
Any Java program is correct Groovy program. So you can add Groovy dependency to your project and then using GroovyShell execute your code:
GroovyShell shell = new GroovyShell();
shell.evaluate(code);
在您的情况下:
GroovyShell shell = new GroovyShell();
shell.evaluate("int i = 10;\n" +
"int j = 2;\n" +
"int k = i*j;\n" +
"System.out.println(\"Result is \" + k);");
并输出:
结果是20
Result is 20
或者您可以使用 ScriptEngineManager p>
Or you can use ScriptEngineManager (more common way):
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("groovy");
engine.eval("int i = 10;\n" +
"int j = 2;\n" +
"int k = i*j;\n" +
"System.out.println(\"Result is \" + k);");
但无论如何,你需要添加Groovy到你的depedencies。
But anyway, you need to add Groovy to your depedencies.
这篇关于执行存储在数据库中的Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!