以为我会试用Nashorn脚本功能。一切正常,我似乎能够从我的.js脚本中调用静态方法,如下所示:
var fun3 = function() {
print("Another day!");
var Go = Java.type('somePack.Go');
var result = Go.fun1('John Doe');
print("\n" + result);
}
在我的“Go”java类中:
public static String fun1(String name) {
System.out.format("Hi there from Java, %s", name);
return "greetings from java";
}
但我想做的是使fun1方法非静态,使这成为一个实例化方法。
public String fun1(String name) {
System.out.format("Hi there from Java, %s", name);
return "greetings from java";
}
在我的script.js中我尝试过:
var Go = new Java.type('somePack.Go');
但我收到错误:
Caused by: <eval>:19 TypeError: function type() { [native code] } is not a constructor function
有没有一种简单的方法可以实现我的目标?
由于
完整筹码:
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
at somePack.Go.go(Go.java:35)
at somePack.Go.main(Go.java:16)
Caused by: <eval>:19 TypeError: function type() { [native code] } is not a constructor function
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:213)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:185)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:172)
at jdk.nashorn.internal.runtime.ScriptFunctionData.getBestConstructor(ScriptFunctionData.java:244)
at jdk.nashorn.internal.runtime.ScriptFunction.findNewMethod(ScriptFunction.java:758)
at jdk.nashorn.internal.runtime.ScriptObject.lookup(ScriptObject.java:1827)
at jdk.nashorn.internal.runtime.linker.NashornLinker.getGuardedInvocation(NashornLinker.java:104)
at jdk.nashorn.internal.runtime.linker.NashornLinker.getGuardedInvocation(NashornLinker.java:98)
at jdk.internal.dynalink.support.CompositeTypeBasedGuardingDynamicLinker.getGuardedInvocation(CompositeTypeBasedGuardingDynamicLinker.java:176)
at jdk.internal.dynalink.support.CompositeGuardingDynamicLinker.getGuardedInvocation(CompositeGuardingDynamicLinker.java:124)
at jdk.internal.dynalink.support.LinkerServicesImpl.getGuardedInvocation(LinkerServicesImpl.java:154)
at jdk.internal.dynalink.DynamicLinker.relink(DynamicLinker.java:253)
at jdk.nashorn.internal.scripts.Script$Recompilation$2$384$\^eval\_.fun3(<eval>:19)
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:386)
答案 0 :(得分:2)
你应该使用
var Go = Java.type('somePack.Go');
var goObject = new Go();