Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!