Java 6 can also run JavaScript)

Source: Internet
Author: User

Inject script language vigor into Java SE <br/> new features of Mustang script language </P> <p> document options </P> <p> send this page as an email </P> <p> send this page as an email </P> <p> level: intermediate </P> <p> Wu weiyun (wuyuehao@cn.ibm.com), software engineer, IBM </P> <p> October 30, 2006 </P> <p> added support for the scripting language in the forthcoming Java se6 (Mustang. By calling the script language, some functions that are usually difficult to implement in Java become simple and lightweight. The interoperability between the scripting language and Java will become elegant and direct. </P> <p> scripting language and Java </P> <p> assume that we have a simple requirement to check the number of words in a document consisting of five letters. Java is generally implemented as follows: </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. filereader; <br/> Import Java. io. ioexception; </P> <p> public class find5words {<br/> Public static void main (string [] ARGs) throws ioexception {<br/> string result = ""; <br/> string line = NULL; <br/> int num = 0; <br/> filereader Fr = new filereader ("FILENAME "); <br/> bufferedreader BR = new bufferedreader (FR); <br/> while (L INE = Br. Readline ())! = NULL) {<br/> result + = line; <br/>}< br/> Br. close (); <br/> Fr. close (); <br/> string [] S = result. split (""); <br/> for (INT I = 0; I <S. length; I ++) {<br/> If (s [I]. matches ("^ // W {5} $") {<br/> num ++; <br/>}< br/> system. out. println (Num); <br/>}</P> <p> check the code that implements the same functions in Perl: </P> <p> open file, "<FILENAME"; <br/> while (<File>) {<br/> for (split) {<br/> $ num ++ if/^/W {5 }$/<br/ >}< Br/> Print $ num; </P> <p> is there an elegant way to combine Java with the scripting language, this will become a reality in the upcoming release of Java se6 (codenamed Mustang) this fall. </P> <p> back to the top </P> <p> Mustang Script Engine </P> <p> JSR 233 designed a set of scripting language APIs for Java. This API provides interfaces for calling various script language engines in Java programs. Any scripting engine that implements this interface can be called in a Java program. The Mustang release includes a Javascript script engine based on Mozilla rhino. </P> <p> Mozilla rhino </P> <p> rhino is a pure Java open-source JavaScript implementation. His name comes from the cover of o'reilly's book about Javascript: </P> <p> the rhino project can be traced back to 1997. At that time, Netscape planned to develop a Java-only navigator, therefore, a Java-implemented JavaScript-javagator is required. It is also the predecessor of rhino. At first, rhino compiled Javascript into a Java binary code for execution, so that it would have the best performance. Later, due to the garbage collection problem in the method of compilation and execution, and the overhead of the compilation and loading process is too large to meet the needs of some projects, rhino provides a way to explain the execution. With the open source code of rhino, more and more users have used rhino in their own products. At the same time, more and more developers have participated in rhino development and made great contributions. Today, rhino1.6r2 will be included in Java se6. more java developers will benefit from this. </P> <p> rhino provides the following functions </P> <p> fully supports JavaScript 1.5 <br/> using JavaScript directly in Java <br/> A JavaScript shell is used to run a Javascript script <br/> A JavaScript compiler, it is used to compile Javascript into a Java binary file <br/> supported scripting language </P> <p> the official script engine implementation project can be found in dev.java.net. This project is based on BSD license, indicating that these script engines are very free to use. Currently, this project supports more than 20 scripting languages, including groovy, JavaScript, Python, Ruby, and PHP. The support list will be expanded. </P> <p> the factory mode is used for script engine search in Mustang. First, you need to instantiate a factory-scriptenginemanager. </P> <p> // create a script engine manager <br/> scriptenginemanager factory = new scriptenginemanager (); </P> <p> scriptenginemanager finds available script Engines Based on the META-INF of the JAR file in the classpath of thread context classloader. It provides three methods to retrieve the Script Engine: </P> <p> // create engine by name <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> // create engine by name <br/> scriptengine engine = factory. getenginebyextension ("JS"); <br/> // create engine by name <br/> scriptengine engine = factory. getenginebymimetype ("application/JavaScript "); </P> <p> the following code prints all script engines supported by the current JDK </P> <p> scriptenginemanager factory = New SC Riptenginemanager (); <br/> for (scriptenginefactory available: factory. getenginefactories () {<br/> system. out. println (available. getenginename (); <br/>}</P> <p> the following section uses JavaScript as an example. </P> <p> explain the script in Java </P> <p> with the script engine instance, you can easily execute the script language, let's start with a simple hello World: </P> <p> public class runjavascript {<br/> Public static void main (string [] ARGs) {<br/> scriptenginemanager factory = new scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> engine. eval ("Print ('Hello World ')"); <br/>}</P> <p> This Java code runs JavaScript and prints Hello world. What if a syntax error occurs in JavaScript? </P> <p> engine. eval ("If (true) {println ('hello')"); </P> <p> intentionally did not add "}", java will throw a javax. script. scriptexception and accurately print the error message: exception in thread "Main" javax. script. scriptexception: <br/> sun.org. mozilla. javaScript. internal. evaluatorexception: <br/> MISSING} in compound statement (<Unknown Source> #1) in <Unknown Source> <br/> at line number 1 <br/>... </P> <p> what if we want to explain some more complex scripting languages or want to change the script at runtime? The script engine supports an overloaded eval method, which can read the required script from a reader: </P> <p> scriptenginemanager factory = new scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> engine. eval (new reader ("helloworld. JS "); </P> <p> As a result, this Java code dynamically searches for helloworld at runtime. javaScript code execution. You can change the Java code behavior by changing the script file at any time. In a simple experiment, the Java code is as follows: public class runjavascript {<br/> Public static void main (string [] ARGs) throws filenotfoundexception, <br/> scriptexception, interruptedexception {<br/> scriptenginemanager factory = new scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> while (true) {<br/> engine. eval (New filereader ("helloworld. JS "); <br/> thread. sleep (1000); <B R/>}< br/>}</P> <p> helloworld. JS content is a simple print of Hello World: Print ('Hello World'); </P> <p> running runjavascript will print a hello World every second. Modify helloworld. JS content is print ('Hello Tony '); </P> <p> the printed content is changed to hello Tony. Therefore, the Java program will dynamically read the script file and explain the execution. For this simple hello World script, Io operations will lose about 20% of the performance (on my Think Pad) than direct execution of the script ), but the flexibility he brings-the ability to dynamically change code at runtime is very exciting on some occasions. </P> <p> communication between the scripting language and Java </P> <p> the PUT Method of scriptengine is used to map a Java object into a variable of the scripting language. Now there is a Java class with only one method. The function is to print a string Hello World: </P> <p> package Tony; </P> <p> public class helloworld {<br/> string S = "Hello World"; <br/> Public void sayhello () {<br/> system. out. println (s); <br/>}</P> <p> How do I use this class in the scripting language? The put method can be: </P> <p> Import javax. script. scriptengine; <br/> Import javax. script. scriptenginemanager; <br/> Import javax. script. scriptexception; </P> <p> public class testput {<br/> Public static void main (string [] ARGs) throws scriptexception {<br/> scriptenginemanager factory = new scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> helloworld Hello = new El Loworld (); <br/> engine. put ("script_hello", hello); <br/> engine. eval ("script_hello.sayhello ()"); <br/>}</P> <p> first, we instantiate a helloworld, then, use the PUT Method to map this instance to the script_hello variable in the scripting language. Then we can call the method of this instance in the eval () function in the same way as in the Java program. Similarly, if we have a script function that performs certain calculations and returns values, we can also conveniently call this script in Java code: </P> <p> package Tony; </P> <p> Import javax. script. invocable; <br/> Import javax. script. scriptengine; <br/> Import javax. script. scriptenginemanager; <br/> Import javax. script. scriptexception; </P> <p> public class testinv {<br/> Public static void main (string [] ARGs) throws scriptexception, <br/> nosuchmethodexception {<br/> scriptenginemanager Factory = New scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> string script = "function say (first, second) {print (first +'' + second );}"; <br/> engine. eval (SCRIPT); <br/> invocable inv = (invocable) engine; <br/> Inv. invokefunction ("say", "hello", "Tony "); <br/>}</P> <p> in this example, we first define a script function say, it is used to concatenate two string parameters and return them. The first time we met one of the two optional interfaces of scriptengine -- invocable, invocable indicates that the current engine can be called as a function. Here we forcibly convert the engine to the invocable type, and use the invokefunction method to pass the parameters to the script engine. Invokefunction defines variable parameters. Multiple parameters can be passed at a time and the return value of the script language is used as the return value. The following example uses JavaScript to implement a simple Max function. It accepts two parameters and returns a large one. To facilitate the correctness of the asserted results, JUnit testcase is inherited here. For details about JUnit, refer to www.junit.org. </P> <p> package Tony; </P> <p> Import javax. script. invocable; <br/> Import javax. script. scriptengine; <br/> Import javax. script. scriptenginemanager; <br/> Import javax. script. scriptexception; <br/> Import JUnit. framework. testcase; </P> <p> public class testscripting extends testcase {</P> <p> Public void testinv () throws scriptexception, nosuchmethodexception {<br/> scriptenginemanager factory = new scripteng Inemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> string script = "function max (first, second)" <br/> + "{return (first> second )? First: Second;} "; <br/> engine. eval (SCRIPT); <br/> invocable inv = (invocable) engine; <br/> Object OBJ = Inv. invokefunction ("Max", "1", "0"); <br/> assertequals ("1", obj. tostring (); <br/>}</P> <p> the invocable interface also has a method for obtaining a Java interface instance from an engine, it is defined as follows: </P> <p> <t> T getinterface (class <t> clasz) </P> <p> it accepts a Java interface type as a parameter and returns an instance of this interface. That is to say, you can use the scripting language to write all the implementations of a Java interface. The following is an example. First, define a Java interface, which has two simple functions: calculate the maximum value and the minimum value: </P> <p> package Tony; </P> <p> Public interface maxmin {<br/> Public int max (int A, int B); <br/> Public int min (int, int B); <br/>}</P> <p> the testcase implements the maxmin interface using JavaScript, returns an instance using the getinterface method, and verifies the result. </P> <p> Public void testinvinterface () throws scriptexception, <br/> nosuchmethodexception {<br/> scriptenginemanager factory = new scriptenginemanager (); <br/> scriptengine engine = factory. getenginebyname ("JavaScript"); <br/> string script = "function max (first, second)" <br/> + "{return (first> second )? First: Second;} "; <br/> script + =" function min (first, second) {return (first <second )? First: Second;} "; <br/> engine. eval (SCRIPT); <br/> invocable inv = (invocable) engine; <br/> maxmin = Inv. getinterface (maxmin. class); <br/> assertequals (1, maxmin. max (1, 0); <br/> assertequals (0, maxmin. min (1, 0); <br/>}</P> <p> script compilation and execution </P> <p> so far, all our scripts are interpreted and executed. In comparison, compilation and execution will achieve better performance. The following describes compilable, another optional interface of scriptengine. The script engine that implements this interface supports script compilation and execution. The following example shows a script to determine whether a given string is an email address or an IP address: </P> <p> Public void testcomplie () throws scriptexception {<br/> scriptenginemanager manager = new scriptenginemanager (); <br/> scriptengine engine = manager. getenginebyname ("JavaScript "); <br/> string script = "Var email =/^ [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-]" <br/> + "+ (//. [a-zA-Z0-9 _-] +) + $ /;"; <br/> script + = "Var IP =/^ (// d {1, 2} | 1 // D // d | 2 [0-4] // d | 25 [0-5]) "<br/> + "(//. (// D {1, 2} | 1 // D // d | 2 [0-4] // d | 25 [0-5]) {3} $ /; "; <br/> script + =" If (email. test (STR) {println ('It is an email ')} "<br/> +" else if (IP. test (STR) {println ('It is an IP address ')} "<br/> +" else {println (' I Don //'t know ')} "; <br/> engine. put ("str", "email@address.tony"); <br/> compilable = (compilable) engine; <br/> compiledscript compiled = compilable. compile (SCRIPT); <br/> compiled. E Val (); <br/>}</P> <p> the script compilation process is as follows: first, convert the engine to the compilable interface, then, call the compilable interface's compile method to obtain a compiledscript instance. This instance represents a compiled script. Using the eval method of compiledscript is used to call the compiled script. On my Think Pad, the compiled call of this Code is about 3-4 times faster than calling engine. Eval directly. As the complexity of the script increases, the performance increases significantly. </P> <p> script context and binding </P> <p> what really associates the script language with Java is not scriptengine, but scriptcontext, it serves as a bridge between Java and scriptengine. </P> <p> A scriptengine has a corresponding scriptcontext, which maintains a map. Each element in this map is a ing between a scripting language object and a Java object. At the same time, this map is also called bindings in our API. A bindings is a map -- Map <string, Object> that specifies that the key must be of the string type. Therefore, a scriptcontext also has a corresponding bindings, which can be obtained and changed through the getbindings and setbindings methods. </P> <p> A bindings includes all the script variables in its scriptcontext. How can we get the value of the script variable? Of course, get from bindings is a method, and scriptcontext also provides the getattribute method, which is obviously very effective when you only want to get a specific script variable value. Setattribute and removeattribute can add, modify, or delete a specific variable. </P> <p> all variables stored in scriptcontext also have their own scopes. They can be engine_scope or global_scope. The former indicates the unique variables of scriptengine, the latter is a common variable of all scriptengine. For example, we run the engine. after the put (Key, value) method, a variable of engine_scope is added. to define a global_scope variable, you can use setattribute (Key, value, scriptcontext. global_scope. </P> <p> In addition, scriptcontext provides the standard input and output redirection function, which can be used to specify the input and output of the script language. </P> <p> back to the top </P> <p> using Java advanced features in Javascript </P> <p> This part is different from the preceding content, this section describes the unique features of the JavaScript engine rhino. </P> <p> using Java objects </P> <p> the previous section describes how to use an instantiated Java object in Javascript, so how to instantiate a Java object in JavaScript? In Java, all classes are stored hierarchically according to the package name. Without this structure in Javascript, rhino uses a clever method to reference all Java objects. Rhino defines a global variable, packages, and all its elements are global variables. This global variable maintains the Java class hierarchy. For example, packages. java. Io. file references the file object in Java's Io package. In this way, we can easily use Java objects in Javascript. Both new and packages can be omitted: </P> <p> // The same: vaR frame = new packages. java. io. file ("FILENAME"); <br/> var frame = Java. io. file ("FILENAME"); </P> <p> we can also reference this object like in Java code: </P> <p> importclass (Java. io. file); <br/> var file = file ("FILENAME"); </P> <p> If You Want To reference all classes in the entire package, you can use importpackage: </P> <p> importpackage (Java. io); </P> <p> If you only need to reference some packages in a specific code segment, you can use javaimporter with Jav Ascript's with keyword, such as: </P> <p> var myimport = javaimporter (Java. io. file); <br/> with (myimport) {<br/> var myfile = file ("FILENAME "); <br/>}</P> <p> A custom package can also be referenced. However, the packages reference cannot be omitted at this time: </P> <p> importpackage (packages. tony); <br/> var Hello = helloworld (); <br/> hello. sayhello (); </P> <p> note that only public members and methods are visible in Javascript, for example, hello. s reference will get undefined. The following briefly introduces some common features: </P> <p> using a Java array </P> <p> it must be constructed using reflection: </P> <p> var A = Java. lang. reflect. array. newinstance (Java. lang. string, 5); </P> <p> in most cases, JavaScript Arrays can be used. When a JavaScript array is passed as a parameter to a Java method, rhino performs automatic conversion and converts it to a Java array. </P> <p> implement a Java interface </P> <p> in addition to the getinterface method of the invocable interface mentioned above, we can also use the following method in the script: </P> <p> // define a javascript object which has corresponding method <br/> OBJ = {max: function (a, B) {return (A> B )? A: B ;}}; <br/> // pass this object to an interface <br/> maximpl = com. tony. maxmin (OBJ); <br/> // invocation <br/> Print (maximpl. max (); </P> <p> If an interface has only one method to implement, you can pass a function as a parameter in javascript: </P> <p> function func () {<br/> println ("Hello World"); <br/>}< br/> T = Java. lang. thread (func); <br/> T. start (); </P> <p> JavaBean support </P> <p> rhino will automatically match the get and is methods of JavaBean, for example, calling hello. string. If the variable string does not exist, rhino The isstring method of the instance is automatically matched, and then the getstring method is matched. If neither method exists, undefined is returned. </P> <p> back to the top </P> <p> command line tool jrunscript </P> <p> In the Mustang release version command line tool, it can explain all the script languages currently supported by JDK. It is also a good tool for learning scripting languages. You can. </P> <p> back to the top </P> <p> conclusion </P> <p> the script language sacrifices the execution speed for higher productivity and flexibility. As computer performance continues to improve and hardware prices continue to decline, it is foreseeable that the scripting language will be widely used. Adding support for the script language in the next version of javase will undoubtedly make Java programs more flexible and make Java programmers work more efficiently. </P> <p> references </P> <p> JSR 233 home page http://www.jcp.org/en/jsr/detail? Id = 223 you can find detailed information about this request here. </P> <p> Mozilla rhino project home page http://www.mozilla.org/rhino/ has a comprehensive project documentation and can download to the latest release of the project and source code. </P> <p> average. You can also find the webpage link of the script engine. </P> <p> the http://www.opensource.org/licenses/ can find details about open source license here. </P> <p> http://www.junit.org/is the official site of JUnit </P> <p> http://java.sun.com/javase/6/docs/is an online Java se6 documentation </P> <p> about the author </P> <p> Wu Xiaoyu, he is currently working in the harmony development team of the IBM China Development Center. In addition to his passion for Java and scripting, his interests include philosophy, mythology, history, and basketball. He is also a computer player. You can contact him via wuyuehao@cn.ibm.com. </P> <p> original address http://www.ibm.com/developerworks/cn/java/j-lo-mustang-script/index.html <br/>

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.