Is there a language-independent way to add a function to JSR223 scripting bindings?

流过昼夜 提交于 2019-12-19 09:57:21

问题


The JSR223 Bindings class allows you to expose arbitrary Java objects to scripting languages. But they have to be objects. I would like to define a function quit() that can be called from the scripting environment that turns into quitObject.run() in Java. But JSR223 doesn't define the concept of a function object. Is there a language-independent way to do the following in Javascript, namely to take a Runnable() and create a function in the scripting environment?

 static private Object asFunction(ScriptEngine engine, Runnable r) 
    throws ScriptException
 { 
        final Bindings bindings = engine.createBindings();
        bindings.put("r", r);
        return engine.eval(
          "(function (r) { var f = function() { r.run(); }; return f;})(r)",
          bindings);
 }

 Runnable quitObject = /* get/create a Runnable here */
 Bindings bindings = engine.createBindings();
 bindings.put("quit", asFunction(engine, quitObject));  

With the builtin Javascript support for JSR223 this creates a sun.org.mozilla.javascript.internal.InterpretedFunction which does what I want. But it obviously won't work in Jython or whatever, and I'd like to make this language-independent.

I don't want my script users to have to type quitObject.run() as that's clumsy, and I don't want to parse script input to find quit() as it could be buried within other code.


回答1:


If you look at javascript engine source code you'll find how oracle/sun implemented 2 functions (print, and println) which are magically (or not so magically) present when you fire up your engine.

Those function are 'scripted' , which is more or less what you did.

What I would do is : load and evaluate a bootstrap.[language_extension] before evaluating any other input in the new context.

You could easily create such scripts for each language you intend to support.



来源:https://stackoverflow.com/questions/13571169/is-there-a-language-independent-way-to-add-a-function-to-jsr223-scripting-bindin

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