My curent JavaScript looks like this:
我的cnt JavaScript看起来像这样:
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
在Java端接收我试图调用的jdk.nashorn.internal.runtime.ScriptFunction
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 个解决方案
#1
4
Don't pass functions between Nashorn and Java. Pass objects which implement functional interfaces.
不要在Nashorn和Java之间传递函数。传递实现功能接口的对象。
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.
我假设o.timer是用Java实现的。在这种情况下,将其参数设置为Runnable(函数的通用函数接口,它不接受任何操作并且不返回任何内容)。 Nashorn将检测到Java需要一个功能接口,并且能够自动将该函数转换为实现该接口的匿名类,因此您无需更改Javascript代码中的任何内容即可实现此功能。
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.
在Java代码中,您可以使用.run()执行该Runnable的脚本函数。然后,javascript代码将在创建它的脚本上下文中执行。
#1
4
Don't pass functions between Nashorn and Java. Pass objects which implement functional interfaces.
不要在Nashorn和Java之间传递函数。传递实现功能接口的对象。
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.
我假设o.timer是用Java实现的。在这种情况下,将其参数设置为Runnable(函数的通用函数接口,它不接受任何操作并且不返回任何内容)。 Nashorn将检测到Java需要一个功能接口,并且能够自动将该函数转换为实现该接口的匿名类,因此您无需更改Javascript代码中的任何内容即可实现此功能。
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.
在Java代码中,您可以使用.run()执行该Runnable的脚本函数。然后,javascript代码将在创建它的脚本上下文中执行。