Is there a language-independent way to add a funct

2019-02-19 02:40发布

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条回答
不美不萌又怎样
2楼-- · 2019-02-19 03:15

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.

查看更多
登录 后发表回答