3 features of the scripting language:
1, Flexible: scripting language is generally dynamic type, you can not declare the variable type directly use, can also change the type at run time;
2, Convenient: scripting language is an explanatory language, changes in the run time is very convenient, without restarting the service
3, simple: scripting language syntax is relatively simple, easy to learn
Additionally: JavaScript is supported by default for JAVA6 above
Example:
Packagecom.test;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjavax.script.Bindings;Importjavax.script.Invocable;ImportJavax.script.ScriptContext;ImportJavax.script.ScriptEngine;ImportJavax.script.ScriptEngineManager;Importjavax.script.ScriptException;/*** Java Execution scripting language *@authorJD **/ Public classJavaScript { Public Static voidMain (string[] args) {//get a JavaScript execution engineScriptEngine SE =NewScriptenginemanager (). Getenginebyname ("JavaScript"); //declaring context variablesBindings bind =se.createbindings (); Bind.put ("Variable", "Result:"); //Scope of the variable, within the current engine rangese.setbindings (Bind,scriptcontext.engine_scope); Try { //Execute JS CodeSe.eval (NewFileReader ("E:/model.js")); //whether the method can be called if(SEinstanceofinvocable) {invocable in=(invocable) se; //how to execute JSString result = (string) in.invokefunction ("formula", 2,10); SYSTEM.OUT.PRINTLN (result); } } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(scriptexception e) {e.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } }}
Scenario 1:
function formula (A, b) {
Return variable+ (A*B);
}
Results:
Results: 20
Scenario 2:
function formula (A, b) {
Return variable+ (A+B);
}
Results: 12
Scene...
Therefore, in changing the business, do not need to restart the Java server, you can change the business smoothly, for the frequently changing business, this is a good solution.
Ps:java 6 Not only provides a code-level script built-in, but also provides the Jrunscript command tool, which can play a huge role in batch processing, and do not need to explain the scripting language through the JVM, you can run the script directly through the tool;
Improving the quality of Java programming-(i) variable Business writing using scripting language