在JS中调用java函数时,不可能在不同的范围(全局/引擎)中工作。
engine.eval("function proxy(a){return Java.type('Foo').bar(a);}",engine.getBindings(ScriptContext.GLOBAL_SCOPE));
engine.eval("function withoutProxy(){return Java.type('Foo').bar(m);}",engine.getBindings(ScriptContext.ENGINE_SCOPE));
engine.eval("function withProxy(){return proxy(m);}", engine.getBindings(ScriptContext.ENGINE_SCOPE));
(其中m
是在引擎范围内声明的JS函数)
调用withoutProxy
可以正常工作。但withProxy
抛出
java.lang.ClassCastException: Cannot cast jdk.nashorn.api.scripting.ScriptObjectMirror to java.util.function.Function
at java.lang.invoke.MethodHandleImpl.newClassCastException(MethodHandleImpl.java:361)
at java.lang.invoke.MethodHandleImpl.castReference(MethodHandleImpl.java:356)
at jdk.nashorn.internal.scripts.Script$Recompilation$7$17A$\^eval\_.proxy(<eval>:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:639)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.ScriptObjectMirror.call(ScriptObjectMirror.java:117)
at jdk.nashorn.internal.scripts.Script$Recompilation$6$20$\^eval\_.withProxy(<eval>:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:199)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:383)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
(堆栈跟踪使用1.8.0_102-ea。与jdk1.8.0_05和jdk1.8.0_73相同的异常。)
所以:我做错了什么,是故意还是错误?
答案 0 :(得分:0)
此问题现已通过JDK 9-ea b 147中的http://bugs.java.com/view_bug.do?bug_id=8162839解决,可从https://jdk9.java.net/download/下载