Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

305
Visualizações
How to get fields and invoke methods of js objects, from java, in Graal-JS?

I have been using GraalVM to execute Javascript from java. But i have a problem: I don't know how to get fields or invoke methods of a js object from java. This is my code, 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);
}

Output:

printWidthOf started 
size class is com.oracle.truffle.polyglot.PolyglotMap
size width is null

Then how can i get a field of a PolyglotMap (js object) from java?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I found the solution.

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"));
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda