我正在尝试弄清楚如何将我的 Javascript 函数传递给我的 Java 方法,以便我可以在运行时调用它。
我有以下 Java 方法签名:
public static void createBlock(String domain, String name, String eventType, EventFunction eventHandler)
我是这样从 Javascript 调用它的:
function main() {
BlockManager.createBlock('sarah-egg', 'enderBlock', 'breakBlock', func);
}
function func (event) {
event.world.createExplosion(null, event.pos.getX(), event.pos.getY(), event.pos.getZ, 10, true);
}
我制作了我的 Java 函数式接口(interface) EventFunction,如下所示:
package com.learntomod.event;
@FunctionalInterface
public interface EventFunction<T> {
void fun(T t);
}
当我运行它时,出现以下错误:
Cannot cast jdk.nashorn.internal.objects.ScriptFunctionImpl to com.learntomod.event.EventFunction
我尝试将 EventFunction 更改为 Runnable 并删除该参数,并且成功了。
关于我可能做错了什么有什么想法吗?
最佳答案
好的 - 事实证明,Forge 可能一直都是罪魁祸首。
Forge 在更改类加载器时做了一些奇怪的事情,因此 Java 可能只是没有自动将我的 JS 函数更改为我的 EventFunction 功能接口(interface)类型(或类似的东西)。
无论如何 - 我找到了一个“解决方案” - 我使用了 https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html - 这是 Java Util 的一部分,并且由于 Runnable 起作用,我们决定尝试 Function(它接受一个参数)并且......它起作用了!
现在我的自定义方 block 会在您打破它们时爆炸 ;) https://www.youtube.com/watch?v=7IJVeC48z6I&feature=youtu.be
谢谢大家的帮助!
关于javascript - 使用 Nashorn 将 Javascript 函数作为功能接口(interface)类型传递给 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098502/