在Java中实现eval() [英] ImplementIon of eval() in Java

查看:80
本文介绍了在Java中实现eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与Java中不存在函数eval()的现象有关。在互联网上阅读了一些内容之后,我发现我能做的最好的事情就是创建自己的解析器作为Java函数。但是怎么做呢?我实际需要的是一个函数,它读取上面数组的第一列并一个接一个地返回所有这些值。但请注意,这些值是字符串存储在String数组中,因此是字符串,但它们代表不同类型的对象,比如X1,X2,X3,X3等。

My question has to do with the phenomenon of non existence of function eval() in Java. After a bit of reading on the Internet I found out that the best thing I could do is to create my own parser as a Java function. But how to do that? What I need actually is a function that reads the first column of the above array and returns one after another all these values. Note however that these values are Strings are stored in a String array, thus are Strings, however they represent objects of different types, say X1, X2, X3, X3, etc.

如果我设法读取这个字符串值,比如说x1,作为一个对象,比如说X1,我就可以用它来调用一些与对象有关的函数,比如x1.classifyInstance(等等等等等等等等... );

If I manage to read this String value, say x1, as an object, say X1, I will then be able to use it for calling some object-X1-related functions, like x1.classifyInstance(blah blah blah...);

希望有人知道如何解决这个问题...!

Hope someone here has any idea about how to solve this issue...!

编辑:这个帖子与我的第一篇文章这里

This thread is close-connected with my first post here!

推荐答案

你可以使用 eval() 方法按照noreferrer> ScriptEngine 类将String评估为javascript字符串

You can use the eval() method of ScriptEngine class to evaluate the String as javascript string

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");        
Object result = engine.eval("4*5");
System.out.println("..result..."+String.valueOf(result));

结果= ..结果... 20.0

这篇关于在Java中实现eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆