2

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!

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.