问题
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:
- 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.
- Use a third-party java compiler like Janino, a Java Compiler http://docs.codehaus.org/display/JANINO/Home
- 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