【问题标题】:How to get fields and invoke methods of js objects, from java, in Graal-JS?如何在 Graal-JS 中从 java 中获取 js 对象的字段和调用方法?
【发布时间】:2021-10-08 08:47:31
【问题描述】:

我一直在使用 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 对象)的字段?

【问题讨论】:

    标签: javascript java truffle graalvm


    【解决方案1】:

    我找到了解决办法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多