首页 > 解决方案 > 如何在 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对象)的字段?

标签: javascriptjavatrufflegraalvm

解决方案


我找到了解决方案。

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"));
    }
}

推荐阅读