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.
Here is a tiny example with Java 8 Nashorn that works as a stand-alone script without any packages:
If you just save it in
RunJavaFromJs.java
, then compile and run usingthen you obtain:
The following snippet
outputs
Quickly hacked together from the JavaDocs.
Output
I'm not sure what script manager you are using but with Rhino you can do things like
So with your example you should be able to call it like a static method: