How To Pass Types And Functions To A JSR-223 Script?
Solution 1:
I have no idea on how to solve the issue regarding the new operation (how to avoid the calls to Java.type()).
But when you compile your script, you can assign methods as lambdas:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
Compilable nashorn = (Compilable) scriptEngineManager.getEngineByName( "Nashorn" );
CompiledScript script = nashorn.compile( "print( sin( 3.14 ) ); var log = getLogger( 'foo' );" );
Bindings bindings = new SimpleBindings();
bindings.put( "sin", (DoubleFunction<Double>) Math::sin );
bindings.put( "getLogger", (Function<String,Logger>) Logger::getLogger );
script.eval( bindings );
For the method void bar()
(no arguments, no return value), you have to provide your own functional interface, as the java.util.function
package does not have one for that kind of method.
Unfortunately, this approach seems not to work for not-compiled scripts. And it does not work for all types of lambdas (functional interfaces). I did some experiments, but could not find a pattern yet what works and what not. It is for sure that functional interfaces that define a method throwing a checked exception do not work this way. Also if the functional interface is not public but a private inner interface.
It should be obvious that I omitted the otherwise necessary error handling and try-catch blocks from the sample code above.
Post a Comment for "How To Pass Types And Functions To A JSR-223 Script?"