问题
Currently I'm using Rhino in my application. I need to eval some JavaScript ant get values from it (I don't need to use Java classes through JavaScript). But it is too slow. Maybe there are any ways to use V8 with Java application?
Update:
I have a large collection of objects of different types. I need a flexible mechanism for validation and transformation these objects to the required form (the user should be able to change the rules of validation and transformation (in runtime), ie hardcoding these rules in Java not suitable). Now everything works on Rhino, but performance is bad. I thought of using NodeJS, but it seems that communication with it, object serialization through processes, etc. - these all will cost very much.
回答1:
Are you absolutely sure you really need
eval
? There are very, very few places whereeval
is actually necessary.You can use ProcessBuilder to shell out to any process available to the underlying system. I'd say the odds of it being faster than a Rhino
eval
are low.You might keep a NodeJS process running alongside your app which you communicate with via a socket. That might win a speed race with
eval
in Rhino.
If you give an example of what you're actually trying to achieve, it may be that people can come up with a better approach for you.
回答2:
Have a look at javax.script.ScriptEngine
. It's a standard Java package, allows evals and data binding:
ScriptEngineManager engineMgr = new ScriptEngineManager();
ScriptEngine engine = engineMgr.getEngineByName("JavaScript");
Bindings bindings = engine.createBindings();
String script = "javascript to eval goes here.....";
bindings.put(varName1, value1);
bindings.put(varName2, value2);
Object obj = engine.eval(script, bindings)
来源:https://stackoverflow.com/questions/4719055/javascript-engine-for-java