【发布时间】:2015-09-17 19:22:47
【问题描述】:
我在 Java 8 上探索 Nashorn,它的功能和它为开发人员提供的能力给我留下了深刻的印象。
为了 JavaScript 代码组织的利益,我想我会尝试揭示模块模式。
this._sys =
(function(){
function hello() {
print('hello world!');
}
return {
hello: hello
};
})();
_sys.hello();
将js代码保存在main.js。当我使用 jjs 时,上面的代码完美无缺。
但是当我尝试通过 Groovy/Java 运行相同的代码时,它失败了。有人能知道它为什么会失败吗?
在 Groovy 中测试:
class Test {
public static void main(String[] args) {
def engine = new ScriptEngineManager().getEngineByName("nashorn")
engine.eval(new FileReader("E:/main.js"));
println engine.context.getAttribute("_sys")
def invocable = engine as Invocable
def x = invocable.invokeFunction("this._sys.hello",null)
println x
}
}
错误:
Exception in thread "main" java.lang.NoSuchMethodException: No such function this._sys.hello
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:184)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:508)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:229)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:130)
at Test.main(Test.groovy:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
【问题讨论】:
标签: javascript java groovy java-8 nashorn