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.
LiveConnect is a technique that allows Java and JavaScript to communicate with each other. It allows your Java class to call JavaScript methods and access the JavaScript environment. JavaScript can also access Java objects and invoke methods on them.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ).
To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.
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
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");
}
}
Welcome to Java world
es.sayHi()
hihi
Press any key to continue . . .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With