Java中eval()的实现
我的问题与Java中不存在函数eval()的现象有关。在互联网上阅读了一些内容后,我发现我能做的最好的事情就是创建我自己的解析器作为 Java 函数。但如何做到这一点呢?我实际上需要的是一个函数,它读取上述数组的第一列并依次返回所有这些值。但请注意,这些值是字符串,存储在字符串数组中,因此是字符串,但它们代表不同类型的对象,例如 X1、X2、X3、X3 等。
如果我设法读取此字符串值,例如 x1,则为一个对象,比如 X1,然后我将能够使用它来调用一些与对象 X1 相关的函数,例如 x1.classifyInstance(blah blah blah...);
希望这里有人知道如何解决这个问题......!
编辑:该线程与我的第一篇文章此处密切相关!
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.
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...!
EDIT: This thread is close-connected with my first post here!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
eval()
ScriptEngine
类将字符串计算为 javascript 字符串Result =
..result...20.0
You can use the
eval()
method ofScriptEngine
class to evaluate the String as javascript stringResult =
..result...20.0
自己构建 Java 编译器是一项艰巨的工作。基本上,有以下三个选项:
Building a Java compiler yourself is a tremendous work. Basically, there are three options:
为了能够在 Java 中调用对象的方法,您需要该对象的实例,并且需要使用适当的类型声明变量。唯一的其他方法是使用反射来调用该方法。 Java 与 JavaScript 不同:它是强类型的,并且没有鸭子类型。
您可能应该做的是让所有这些对象实现一个通用接口:
并使用以下代码(您需要处理异常,但我省略了它们):
To be able to call a method on an object in Java, you need an instance of this object, and you need to have a variable declared with the appropriate type. The only other way is to use reflection to call the method. Java is not like JavaScript: it's strongly typed, and doesn't have duck typing.
What you should probably do is to make all those objects implement a common interface:
And use the following code (you need to handle the exceptions, but I omitted them):