The scripting language is powerful, needless to say, but how do you invoke the scripting language in Java?
Flexible
Convenient
Simple
These features make the scripting language indispensable in the development process, so JAVA6 begins to formally support the scripting language
However, because of the very many scripting languages, Java developers are also difficult to determine which language to support, so JCP (Java conmunity Process) proposed the JSR223 specification, as long as the language that conforms to the specification can be run on the Java platform
Here's an example of a Java call to JavaScript
function test () {obj,obj2}{
return obj1+obj2+num;
}
The JavaScript is saved in the F:/model.js
public static void Main (string[] args) {
ScriptEngine engine = new Scriptenginemanager (). Getenginebyname ("JavaScript");
Bindings bind = Engine.createbindings ();
Bind.put ("num", 1);
Engine.setbindings (Bind, Scriptcontext.engine_scope);
Scanner input = new Scanner (system.in);
while (Input.hasnextint ()) {
int first = Input.nextint ();
int sec =input.nextint ();
System.out.println (first+ "| "+sec);
try {
Engine.eval (New FileReader ("F:/model.js"));
} catch (FileNotFoundException | Scriptexception e) {
E.printstacktrace ();
}
if (engine instanceof invocable) {
Invocable in = (invocable) engine;
Double result = 0d;
try {
result = (Double) in.invokefunction ("Test", First, SEC);
} catch (Nosuchmethodexception | Scriptexception e) {
E.printstacktrace ();
}
System.out.println (Result.intvalue ());
}
The code above scanner accepts two digits of the keyboard input and then calls the JavaScript test function to calculate the result, which runs as follows:
1
2
1 | 2
4
After modifying the Java code, the JVM does not restart, the input parameters do not change, just change the script function can produce different results, this is the scripting language for the system design is the most advantageous place, can be released at any time without redeployment, And that's where we like him the most-----------even if the changes are made, we can provide uninterrupted business services.
Calling JavaScript in Java