javascript - 如何在 Graal-JS 中从 java 中获取 js 对象的字段和调用方法?
问题描述
我一直在使用 GraalVM 从 java 执行 Javascript。但我有一个问题:我不知道如何从 java 获取字段或调用 js 对象的方法。这是我的代码,java:
public static class JavaMethods {
public void printWidthOf(Object size) {
System.out.println("printWidthOf started");
System.out.println("size class is " + size.getClass().getName()); // prints PolyglotMap
Map map = (Map) size; // PolyglotMap implements Map so i tried that
System.out.println("size width is " + map.get("size")); // doesn't work, prints null instaed of 40
}
}
public static void main(String[] args) throws Exception {
GraalJSEngineFactory factory = new GraalJSEngineFactory();
GraalJSScriptEngine engine = factory.getScriptEngine();
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("polyglot.js.allowHostAccess", true);
bindings.put("JavaMethods", new JavaMethods());
engine.eval(new FileReader("MyScript.js"));
engine.invokeFunction("start");
}
javascript:
class Size {
#width;
#height;
constructor(w, h) {
this.#width = w;
this.#height = h;
}
getWidth() {
return this.#width;
}
getHeight() {
return this.#height;
}
}
function start() {
var mySize = new Size(40, 60);
JavaMethods.printWidthOf(mySize);
}
输出:
printWidthOf started
size class is com.oracle.truffle.polyglot.PolyglotMap
size width is null
那么我如何从java中获取PolyglotMap(js对象)的字段?
解决方案
我找到了解决方案。
public static class JavaMethods {
public void printWidthOf(Object size) throws Exception {
Field f = size.getClass().getDeclaredField("guestObject");
f.setAccessible(true);
JSOrdinaryObject obj = (JSOrdinaryObject) f.get(size);
System.out.println(obj.getValue("width"));
}
}
推荐阅读
- laravel - 如何在 Laravel 中实现授权(Guard),而不使用 make:auth 命令
- php - 为什么没有创建项目?
- rest - 通过 https 使用 kubeconfig 提供 Kubernetes 集群身份验证
- html - 如何防止标签重定向用户,同时保持其 href 属性?
- java - javax.persistence.PersistenceException:没有名为 ZaapMartPU 的 EntityManager 的持久性提供程序
- angular - 哪个 Guard 解雇了 GuardsCheckEnd?
- bash - 如何使用保存和导出进行容器迁移
- android - 我正在尝试在我的设备上获得真实的广告,但应用在我的 Android 应用上显示测试广告
- c# - 使用 Rest API 进行 AWS API 身份验证 - AWS 无法验证提供的访问凭证
- node.js - NestJS 中的单元测试