Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

306
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda