5

My curent JavaScript looks like this:

o.timer(function (){
    //Call from Java
    print("Hello World");
}).start(1000);

On the Java side receive a jdk.nashorn.internal.runtime.ScriptFunction witch I tried to call with

ScriptFunction callback = ...
callback.getBoundInvokeHandle(MethodType.methodType(Object.class)).invoke();

But it throws this:

java.lang.IllegalStateException: no current global instance
at jdk.nashorn.internal.objects.Global.instance(Global.java:474)
at jdk.nashorn.internal.objects.ScriptFunctionImpl.<init>(ScriptFunctionImpl.java:145)
at jdk.nashorn.internal.scripts.Script$\^eval\_._L3(<eval>:6)
at demo.Mainr$1.run(Main.java:38)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

How can I call this function?

1 Answer 1

5

Don't pass functions between Nashorn and Java. Pass objects which implement functional interfaces.

I assume o.timer is implemented in Java. In that case, make its parameter a Runnable (the generic functional interface for a function which takes nothing and returns nothing). Nashorn will detect that Java expects a functional interface and will be able to automatically convert the function to an anonymous class which implements that interface, so you don't have to change anything at your Javascript code to make it do that.

In your Java code you can then execute the script function of that Runnable with .run(). The javascript code will then be executed in the script context in which it was created.

Sign up to request clarification or add additional context in comments.

2 Comments

How to pass arguments to this Runnable call?
@игор When you want to pass something to it, create a new functional interface which takes arguments.

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.