Search code examples
javascriptjavajava-8anonymous-functionnashorn

Java Nashorn - How to define a JavaScript function in Java which accepts an anonymous function as an argument?


Basically what I'm trying to do is to create a new function, which can be used in JavaScript, but it would require a string and an anonymous function to be passed as arguments. The anonymous function would also have to supply an argument of it's own.

In the JavaScript I would like to have:

addEventHandler( "eventName", function ( event ) {
    // do stuff
});

and the way I'd like Java to interpret that is like so:

addEventHandler ( "eventName", event -> {
    // do stuff
});

Is this possible? At all? Thank you in advance!


Solution

  • If you have a Java method that accepts a functional interface as an argument, you can pass an anonymous function in javascript.

    For instance:

    public static void main(String[] args) throws Throwable {
        ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
    
        se.put("myObject", new MyClass());
    
        se.eval("myObject.someMethod('hello', function(e){ print(e); })");
    }
    
    public static class MyClass { // Class needs to be public
        public void someMethod(String s, Consumer<String> cons) {
            System.out.println(s);
            cons.accept("SomeString");
        }       
    }
    

    Prints:

    hello
    SomeString