Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - Add binding to static class Math in graal context

I use e.g.

context.getBindings("js").putMember("thing", new Thing(this));

to define a variable for my javascript.

How can I expose Java's Math """"object""""?

I can't do

context.getBindings("js").putMember("math", Math);

nor

context.getBindings("js").putMember("math", new Math());

(bc the constructor is private)

question from:https://stackoverflow.com/questions/65920175/add-binding-to-static-class-math-in-graal-context

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As discussed in https://github.com/oracle/graaljs/issues/414, you need to:

  • expose Math.class and then access math.static.toRadians()
  • enable HostAccess on the Context you are using

The working example thus is:

try (Context ctx = Context.newBuilder("js").allowHostAccess(HostAccess.ALL).build()) {
        ctx.getBindings("js").putMember("math", Math.class);
        ctx.eval("js", "print(math.static.toRadians(180));");
        ctx.close();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...