Java 中有 eval() 函数吗? [英] Is there an eval() function in Java?
本文介绍了Java 中有 eval() 函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的字符串:
I have a string like the following:
String str = "4*5";
现在我必须使用字符串来获取 20
的结果.
Now I have to get the result of 20
by using the string.
我知道在其他一些语言中,eval()
函数可以做到这一点.我如何在 Java 中执行此操作?
I know in some other languages the eval()
function will do this.
How can I do this in Java?
推荐答案
您可以使用 ScriptEngine
类并将其计算为 Javascript 字符串.
You can use the ScriptEngine
class and evaluate it as a Javascript string.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");
可能有更好的方法,但这个方法有效.
There may be a better way, but this one works.
这篇关于Java 中有 eval() 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文