How can I add methods from a Java class as global functions in Javascript using Rhino?
Posted
by gooli
on Stack Overflow
See other posts from Stack Overflow
or by gooli
Published on 2010-03-31T11:06:48Z
Indexed on
2010/03/31
15:13 UTC
Read the original article
Hit count: 354
I have a simple Java class that has some methods:
public class Utils {
public void deal(String price, int amount) {
// ....
}
public void bid(String price, int amount) {
// ....
}
public void offer(String price, int amount) {
// ....
}
}
I would like to create an instance of this class and allow the Javascript code to call the methods directly, like so:
deal("1.3736", 100000);
bid("1.3735", 500000);
The only way I could figure out for now was to use
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.put("utils", new Utils());
and then use utils.deal(...)
in the Javascript code. I can also write wrapper functions in Javascript for each method, but there should be a simpler way to do this automatically for all the public methods of a class.
© Stack Overflow or respective owner