ImplementIon of eval() in Java [duplicate]

一世执手 提交于 2020-01-20 10:09:06

问题


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!


回答1:


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));

Result = ..result...20.0




回答2:


Building a Java compiler yourself is a tremendous work. Basically, there are three options:

  1. Use ToolProvider.getSystemJavaCompiler(). The second answer at How to create an object from a string in Java (how to eval a string)? also uses this and might give you an idea how to use it.
  2. Use a third-party java compiler like Janino, a Java Compiler http://docs.codehaus.org/display/JANINO/Home
  3. Use a Javascript (or other language) compiler using the ScriptEngineManager and convert a Javascript array to Java.



回答3:


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:

public interface Classifyable {
    void classify();
}

And use the following code (you need to handle the exceptions, but I omitted them):

for (String s : stringArray) {
    // s is the class name of the object to instantiate, right?
    Class<?> clazz = Class.forName(s);
    Classifyable c = (Classifyable) clazz.newInstance(); // calls the no-arg constructor
    c.classify();
}


来源:https://stackoverflow.com/questions/8666935/implemention-of-eval-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!