Java / Nashorn put one function in binding / global scope

I have one static method like:

some abstract class C {
    void dump( Object o ) {
}

which I’d like to pass to js that I can use it directly in the global scope like:

js> dump( new Something() );

So far the only way I found is creating an instance like

public class CStub {
    void dump( Object o ){ C.dump( o ); }
}

putting it in nashorn via:

engine.put( "stub", new CStub() );

and then in js:

js> var dump = stub.dump

but is there another approach to this which doesn’t involve the stub creation and puts the method directly in the global scope?

Answer

You can implement a functional interface (https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html) like java.util.function.Function in your class and expose an object of it as a global variable to nashorn. Nashorn treats any “functional interface” object as a function and allows direct call to it. Simple example that exposes a “dump” function is as follows:

import javax.script.*;
import java.util.function.Function;

public class Main {
   // a Function implementation
   private static class MyFunc implements Function<String, Void> {
       @Override
       public Void apply(String msg) {
           System.out.println(msg);
           return null;
       }
   }

   public static void main(String[] args) throws Exception {
       ScriptEngineManager m = new ScriptEngineManager();
       ScriptEngine e = m.getEngineByName("nashorn");

       // expose functional interface object as a global var
       e.put("dump", new MyFunc());

       // invoke functional interface object like a function!
       e.eval("dump('hello')");
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *