ImplementIon of eval() in Java [duplicate]

孤街醉人 提交于 2019-11-29 18:17:37
Sunil Kumar Sahoo

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

Willem Mulder

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.

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