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
148 views
in Technique[技术] by (71.8m points)

javascript - Rhino: How to call JS function from Java

I'm using Mozilla Rhino 1.7r2 (not the JDK version), and I want to call a JS function from Java.

My JS function is like this:

function abc(x,y)
{
  return x+y
}

How do I do this?

Edit: (The JS function is in a separate file)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
String script = "function abc(x,y) {return x+y;}";
Context context = Context.enter();
try {
    ScriptableObject scope = context.initStandardObjects();
    Scriptable that = context.newObject(scope);
    Function fct = context.compileFunction(scope, script, "script", 1, null);
    Object result = fct.call(
            context, scope, that, new Object[] {2, 3});
    System.out.println(Context.jsToJava(result, int.class));
} finally {
    Context.exit();
}

UPDATE: when the function is loaded in the scope, along with other functions and variables

String script = "function abc(x,y) {return x+y;}"
        + "function def(u,v) {return u-v;}";
Context context = Context.enter();
try {
    ScriptableObject scope = context.initStandardObjects();
    context.evaluateString(scope, script, "script", 1, null);
    Function fct = (Function)scope.get("abc", scope);
    Object result = fct.call(
            context, scope, scope, new Object[] {2, 3});
    System.out.println(Context.jsToJava(result, int.class));
} finally {
    Context.exit();
}

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

2.1m questions

2.1m answers

60 comments

56.9k users

...