Nashorn:名称空间内的调用函数 [英] Nashorn: Call function inside of a namespace

查看:164
本文介绍了Nashorn:名称空间内的调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用NashornScriptEngine评估了以下脚本:

I have evaluated the following script using the NashornScriptEngine:

var Namespace = {
    test: function()
    {
        return "It works";
    }
}

现在我要调用函数test.

Now I want to call the function test.

使用nashorn引擎的方法invokeFunction时,将引发以下异常:

When using the method invokeFunction of the nashorn engine, the following exception is thrown:

java.lang.NoSuchMethodException: No such function Namespace.test

如何调用此函数?

推荐答案

您正在尝试访问名为window["Namespace.test"]而不是window.Namespace.Test的全局函数.您首先需要获得对Namespace的引用,然后可以调用

You are trying to access a global function called window["Namespace.test"], not window.Namespace.Test. You first need to get a reference to Namespace, then you can call invocable.invokeMethod specifying Namespace as its context (this).

例如,要调用JSON.parse(),可以使用以下命令:

For example, to call JSON.parse(), you can use the following:

Object json = engine.eval("JSON"); // Or "Namespace" in your case
Object data = invocable.invokeMethod(json, "parse", contactJson); //"test" for the case you mention

这篇关于Nashorn:名称空间内的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆