如何从 javascript 调用 java 方法
正如标题中所述,我想要实现的目标如下:
- 创建 java 对象
- 将其传递给 JavaScript
- 在传递的对象上调用方法(例如 setter)
- 继续使用 java 中的对象
我正在使用包含在中的脚本爪哇。 如果有人能帮助我解决这个问题,我会很高兴。
As described in the title, what I am trying to achieve is the following:
- Create java object
- Pass it to JavaScript
- Invoke a method (a setter for instance) on the passed object
- Continue work with the object in java
I am using the scripting included in java.
I will be happy if someone can help me with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 ScriptEngine 框架,这非常简单。您可以通过两种方式将 Java 对象“传递”给 JavaScript:
如果需要,您还可以从 JavaScript 访问 Java 构造函数并实例化 Java 对象。
首先,您必须为脚本引擎设置“绑定”。它就像一个 Map:
现在,当 JavaScript 代码在该引擎中运行时,全局符号“foo”将充当对 Java 对象的引用。您可以根据需要绑定任意数量的引用。
如果您想将 Java 对象作为参数传递给 JavaScript 函数,您首先需要的是一种调用 JavaScript 函数的方法。为此,您可以使用“Invocable”接口公开的“invokeFunction”或“invokeMethod”方法:
“上下文”只是您希望
this
在函数中引用的内容的引用这就是所谓的。 “methodName”只是一个字符串,给出全局 JavaScript 函数的名称。Java 类可通过其完全限定路径名供 JavaScript 环境使用:
这将为您提供一个作为 JavaScript 变量的 Java HashMap 实例。
If you're working with the ScriptEngine framework, this is really easy. You can "pass" Java objects to JavaScript in two ways:
You can also access Java constructors from JavaScript and instantiate Java objects if you want.
To do the first thing, you have to set up the "bindings" for the script engine. It's just like a Map:
Now, when JavaScript code runs in that engine, the global symbol "foo" will serve as a reference to a Java object. You can bind in as many references as you like.
If you want to pass a Java object as a parameter to a JavaScript function, the first thing you need is a way to call a JavaScript function. To do that, you use the "invokeFunction" or "invokeMethod" method exposed by the "Invocable" interface:
The "context" there is just a reference to something you want
this
to refer to in the function that's called. The "methodName" is just a string giving the name of your global JavaScript function.Java classes are available to the JavaScript environment via their fully-qualified pathnames:
That would give you a Java HashMap instance as a JavaScript variable.