Monday 8 May 2017

Does node-java allow anonymous functions to be passed to java as parameters?

I want to be able to pass an anonymous function from Javascript to Java using node-java (https://github.com/joeferner/node-java). Here's a sample of the Java code:

public class Example {
    public Example() {
    }

    public interface Callback {
        public void f();
    }

    public void method1(boolean flag, Callback c) {
        System.out.println("flag value: " + flag);
        if (flag) {
            System.out.println("About to call callback");
            c.f();
            System.out.println("Called callback");
        }
        else {
            System.out.println("Didn't call callback");
        }
    }
}

Here's how I want to call it from Javascript:

var java = require('java');
java.classpath.push('test8');

var Example = java.import('Example');

var anonF = () => {
    console.log("Hello from callback!");
}

var e = new Example();
e.method1Sync(true, anonF);

In this case, the anonF function is always called. Not what I want.

I have also tried passing in a Javascript module as parameter, and haven't been able to get that to work. Thoughts?



via Chris Prince

No comments:

Post a Comment