8

The java have a script manager that allow java calling javascript, like this:

import javax.script.*;
public class ExecuteScript {
 public static void main(String[] args) throws Exception {
 // create a script engine manager
 ScriptEngineManager factory = new ScriptEngineManager();
 // create a JavaScript engine
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 // evaluate JavaScript code from String
 engine.eval("print('Welocme to java world')");
 }

 public static void sayHi(){
   System.out.println("hihi");
 }
}

My question is, if I have a sayHi() function, can I use the javascript, via the script engine to call the Java function? Thanks.

0

4 Answers 4

9

The following snippet

package org.test.script;
import javax.script.*;

public class ExecuteScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("" +
            "importPackage(org.test.script);\n" +
            "print('Welocme to java world\\n');\n" +
            "ExecuteScript.sayHi();");
    }

    public static void sayHi() {
        System.out.println("hihi");
    }
}

outputs

Welocme to java world
hihi
Sign up to request clarification or add additional context in comments.

2 Comments

engine.put(.. seems redundant. Agree. Answer's been modified
FYI for y'all out there, importPackage needs an extra line before it to work properly in Java 8: load("nashorn:mozilla_compat.js");
5

Quickly hacked together from the JavaDocs.

import javax.script.*;

public class ExecuteScript {

    public static void main(String[] args) throws Exception {
        // create a Java object
        ExecuteScript es = new ExecuteScript();

        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("println('Welcome to Java world')");

        // add the Java object into the engine.
        engine.put("es",es);

        ScriptEngineFactory sef = engine.getFactory();
        String s = sef.getMethodCallSyntax("es", "sayHi", new String[0]);
        // show the correct way to call the Java method
        System.out.println(s);
        engine.eval(s);
    }

    public static void sayHi(){
        System.out.println("hihi");
    }
}

Output

Welcome to Java world
es.sayHi()
hihi
Press any key to continue . . .

Comments

1

I'm not sure what script manager you are using but with Rhino you can do things like

var date = new java.util.Date();
print(date);

So with your example you should be able to call it like a static method:

ExecuteScript.sayHi();

Comments

1

Here is a tiny example with Java 8 Nashorn that works as a stand-alone script without any packages:

import javax.script.*;
import java.util.LinkedList;

public class RunJavaFromJs {
  public static void main(String[] args) throws Exception {
    LinkedList<Integer> jList = new LinkedList<>();
    jList.add((Integer)42);

    ScriptEngine engine = 
      (new ScriptEngineManager())
      .getEngineByName("nashorn");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("jList", jList);
    engine.eval("" + 
      "load('nashorn:mozilla_compat.js');\n" +
      "// call static method\n" + 
      "var i = Packages.RunJavaFromJs.helloWorld(42);\n" + 
      "// perform side effect\n" + 
      "print('Result was: ' + i + '(printed from JS)');\n" + 
      "// call method on `jList` instance passed in bindings \n" +
      "jList.add(12345);\n" +
      "print(jList.toString());"
    );
  }
  public static int helloWorld(int x) {
    System.out.println("Hello, world! (printed from Java in static method)");
    return x * x;
  }
}

If you just save it in RunJavaFromJs.java, then compile and run using

javac RunJavaFromJs.java && java RunJavaFromJs

then you obtain:

Hello, world! (printed from Java in static method)
Result was: 1764(printed from JS)
[42, 12345]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.