The script engine of javase 6 makes programs even more powerful.

Source: Internet
Author: User
Tags try catch java se
 

One of the most striking new features of Java SE 6 is script support embedded. By default, Java SE 6 only supports JavaScript, but this does not mean that Java SE 6 only supports JavaScript. Java SE 6 provides some interfaces to define a script specification, namely jsr223. By implementing these interfaces, Java SE 6 can support any scripting language (such as PHP or Ruby ).

Run the first script program

Before using Java SE 6 to run scripts, you must know the scripting languages supported by Java SE 6. There are many classes in the javax. Script package, but the most important of these classes is scriptenginemanager. You can use this class to obtain all scripts supported by Java SE 6. The following example lists all the Script Engine factories that can be used.

Import javax. script. *; import Java. io. *; import Java. util. *; import static Java. lang. system. *; public class listscriptengines {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); // obtain all the Script Engine Factory list factories = manager. getenginefactories (); // This Is The New for statement syntax for Java SE 5 and Java SE 6 (scriptenginefactory Factory: factories) {// print the script information out. printf ("Name: % S % N" + "Version: % S % N" + "language name: % S % N" + "language version: % S % N" + "extensions: % S % N "+" MIME types: % S % N "+" names: % S % N ", factory. getenginename (), factory. getengineversion (), factory. getregistragename (), factory. getlanguageversion (), factory. getextensions (), factory. getmimetypes (), factory. getnames (); // obtain the current Script Engine scriptengine engine = factory. the example above getscriptengine ();} // For} // main} must be in Java SE 6. Here, import static java. Lang. system. * is the new syntax. It references all static members in the system and can be used directly in the future.

By running Java listscriptengines, the following information is displayed:

Name: Mozilla rhino

Version: 1.6 Release 2

Language name: ecmascript

Language Version: 1.6

Extensions: [JS]

MIME types: [application/JavaScript, application/ecmascript, text/JavaScript, text/ecmascript]

Names: [JS, Rhino, JavaScript, JavaScript, ecmascript, ecmascript]

The bottom line is the alias of the script, that is, any of them can be used. There are three methods to obtain a specific script engine.

· Get the script engine based on the extension

Scriptengine engine = manager. getenginebyextension ("JS ");

The parameter of getenginebyextension is extensions: [JS] […] .

· Obtain the Script Engine Based on the MIME type

Scriptengine engine = manager. getenginebymimetype ("text/JavaScript ");

The getenginebymimetype parameter can be MIME types: [application/JavaScript, application/ecmascript, text/JavaScript,

In text/ecmascript], you can change text/JavaScript to text/ecmascript.

· Obtain the script engine by name

Scriptengine engine = manager. getenginebyname ("JavaScript ");

The parameter after getenginebyname can be names: Any one of [JS, Rhino, JavaScript, JavaScript, ecmascript, ecmascript,

For example, you can change JavaScript to ecmascript.

The first step in script execution is to get an available script engine. You can use the script engine to execute the corresponding script after completing this task. We can use the eval method of scriptengine to execute the script. The eval method is overloaded multiple times, but the most commonly used is the public object eval (string script ).

The following example demonstrates how to use the eval method to execute JavaScript scripts.

Import javax. script. *; import Java. io. *; import static Java. lang. system. *; public class firstjavascript {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); // obtain the Javascript script engine scriptengine engine = manager. getenginebyname ("JavaScript"); try {// start to run the script and return the current hour double hour = (double) engine. eval ("Var date = new date ();" + "date. gethours (); "); string MSG; // converts an hour to a greeting message if (hour <10) {MSG =" good morning ";} else if (hour> 10 & hour <16) {MSG = "Good noon";} else if (hour> 16) {MSG = "Good afternoon ";} else if (hour <20) {MSG = "Good evening";} else {MSG = "good night";} Out. printf ("hour % s: % S % N", hour, MSG);} // try catch (scriptexception e) {err. println (e) ;}// main}
 
In the preceding example, the current hour is obtained and converted to a greeting. The output information of the above program is:

9.0 hours: Good morning

In this example, two scripts are executed, and the last one is date. gethours (). This value is not assigned to a javascript variable. In this case, the eval method returns such a value. This is similar to the C language (...) Operator. For example, (C = A + B, C + D), the return value of this expression is A + B + D.

Interaction with scripting language

The above example only runs a very simple script. This script is isolated and does not pass any value to this script through Java. Although a value is returned from this script, this return method is implicit.

In addition to these simple functions, the script engine also provides us with more powerful functions. You can even pass parameters to the scripting language through Java, and obtain the values of variables in the scripting language. These functions depend on the put and get methods in scriptengine.

Put has two parameters: one is the script variable name and the other is the variable value. This value is of the object type. Therefore, any value can be passed.

Get has a parameter, that is, the name of the script variable.

The following code uses a Javascript script to flip a string (this string is passed to JavaScript through Java), and then uses Java to get the character after being flipped, and then outputs it.

Import javax. script. *; import Java. io. *; import static Java. lang. system. *; public class reversestring {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); // create a Javascript script engine scriptengine engine = manager. getenginebyname ("JavaScript"); try {// pass the variable name and variable value abcdefg to the Javascript script engine. put ("name", "abcdefg"); // start to execute the script engine. eval ("Var output =''; "+" for (I = 0; I <= Name. length; I ++) {"+" output = Name. charat (I) + output "+"} "); // obtain the value of the output variable string name = (string) engine. get ("output"); out. printf ("flipped string: % s", name);} catch (scriptexception e) {err. println (e );}}}

The output result of the above Code is: the string after the flip: gfedcba

Make the script run faster

As we all know, interpreting the running mode is the slowest running mode. The preceding examples are all interpreted. Java EE 6's script engine supports any language that implements the Script Engine interface. Many of these languages provide the compilation function. That is to say, you must compile these scripts before running the script. (The compilation here is generally not to generate executable files, instead, compile the code in the memory to make it easier to run) and then execute the code. If you want to run a script multiple times, this method is very fast. We can use the compile method of scriptengine for compilation. Not all script engines support Compilation. Only the script engine that implements the compilable interface can use compile for compilation. Otherwise, an error will be thrown. The following example shows how to use the compile method to compile and run JavaScript scripts.

Import javax. script. *; import Java. io. *; import static Java. lang. system. *; public class compilescript {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); scriptengine engine = manager. getenginebyname ("JavaScript"); Engine. put ("counter", 0); // pass a parameter to JavaScript // determine whether the Script Engine supports the compilation function if (engine instanceof compilable) {compilable compengine = (compilable ) Engine; try {// compile compiledscript script = compengine. compile ("function count () {" + "counter = counter + 1;" + "return counter;" + "}; count ();"); out. printf ("counter: % S % N", script. eval (); out. printf ("counter: % S % N", script. eval (); out. printf ("counter: % S % N", script. eval ();} catch (scriptexception e) {err. println (e) ;}} else {err. println ("this script engine does not support Compilation! ");}}}

The following information is displayed after the code is run:

Counter: 1.0

Counter: 2.0

Counter: 3.0

In this example, compile the script using the compile method, and then call it multiple times using the eval method. In this Code, there is only one function. Therefore, Eval returns the value of this function.

Dynamic Method for calling the script language

In the preceding example, there is only one function that can be called through eval and return its value. However, if there are multiple functions in the script or you want to use user input to determine which function to call, you need to use the invoke Method for Dynamic calling. Like compiling, the script engine must implement the invocable interface to dynamically call methods in the script language. The following example shows how to run the Javascript script for string flip by using dynamic calling.

Import javax. script. *; import Java. io. *; import static Java. lang. system. *; public class invocabletest {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); scriptengine engine = manager. getenginebyname ("JavaScript"); string name = "abcdefg"; if (engine instanceof invocable) {try {engine. eval ("function reverse (name) {" + "Var output =''; "+" for (I = 0; I <= Name. length; I ++) {"+" output = Name. charat (I) + output "+"} return output;} "); invocable invokeengine = (invocable) engine; object o = invokeengine. invokefunction ("reverse", name); out. printf ("flipped string: % s", O);} catch (nosuchmethodexception e) {err. println (E);} catch (scriptexception e) {err. println (e) ;}} else {err. println ("this script engine does not support dynamic calling ");}}

Dynamic implementation Interface

The script engine also has a more attractive feature, that is, the dynamic implementation interface. For example, if we want the script to be executed asynchronously, that is, through multithreading, The invokeengine class must implement the runnable interface to start multithreading through thread. Therefore, you can use the getinterface method to enable invokeengine to dynamically implement the runnable interface. This can be divided into three steps.

1. Use JavaScript to compile a run Function

Engine. eval ("function run () {print (asynchronous execution );}");

2. Use the getinterface method to implement the runnable interface

Runnable runner = invokeengine. getinterface (runnable. Class );

3. Use the Thread class to start Multithreading

Thread t = new thread (runner );

T. Start ();

The following is the detailed code to implement this function.

Import javax. script. *; import static Java. lang. system. *; public class interfacetest {public static void main (string ARGs []) {scriptenginemanager manager = new scriptenginemanager (); scriptengine engine = manager. getenginebyname ("JavaScript"); try {engine. eval ("function run () {print (asynchronous call) ;}"); invocable invokeengine = (invocable) engine; runnable runner = invokeengine. getinterface (runnable. class); thread t = new thread (runner); T. start (); T. join ();} catch (interruptedexception e) {err. println (E);} catch (scriptexception e) {system. err. println (e );}}}

In fact, the above Code implements the run method of the runnable interface through JavaScript.

 

From: http://tech.it168.com/jd/2008-07-04/200807041154728.shtml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.