JavaScript engine for Java

那年仲夏 提交于 2019-12-22 23:33:11

问题


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:


  1. Are you absolutely sure you really need eval? There are very, very few places where eval is actually necessary.

  2. 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.

  3. 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

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