JavaScriptingProgrammersGuide.html revision 408:29b2b2ed954c
185378Sjlemon<!-- 285378Sjlemon Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3298107Sgjb DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 485378Sjlemon 585378Sjlemon This code is free software; you can redistribute it and/or modify it 6198236Sru under the terms of the GNU General Public License version 2 only, as 785378Sjlemon published by the Free Software Foundation. Oracle designates this 885378Sjlemon particular file as subject to the "Classpath" exception as provided 9 by Oracle in the LICENSE file that accompanied this code. 10 11 This code is distributed in the hope that it will be useful, but WITHOUT 12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 version 2 for more details (a copy is included in the LICENSE file that 15 accompanied this code). 16 17 You should have received a copy of the GNU General Public License version 18 2 along with this work; if not, write to the Free Software Foundation, 19 Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 21 Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 or visit www.oracle.com if you need additional information or have any 23 questions. 24--> 25<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 26<html class=" regenabled gecko radius jsenabled regloaded" xmlns="http://www.w3.org/1999/xhtml"><head> 27<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 28<title>Java Scripting Programmer's Guide</title> 29 30<!-- ============ --> 31<!-- MAIN CONTENT --> 32<!-- ============ --> 33<table summary="layout" border="0" width="100%"> 34<tbody><tr> 35<td> 36 37<div id="sharepage" class="smallpagetitle"><h1>Java Scripting Programmer's Guide</h1><div class="sharepage"> <div class="sharepagew1 share-mailto"> <table summary="" cellpadding="0" cellspacing="0"><tbody><tr> <td id="share-mailto"><a href="mailto:?subject=Java%20Documentation%20Page:%20Java%20Scripting%20Programmer%27s%20Guide&body=Check%20out%20this%20page:%20%0A%0Ahttp%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html" class="sharelink mailto" title="Email this page to a friend"></a></td> <td id="share-technorati"><a href="http://technorati.com/search/http%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html" class="sharelink technorati" title="See who links to this page on Technorati"></a></td> <td id="share-delicious"><a href="http://del.icio.us/post?v=4;url=http%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html;title=Java%20Scripting%20Programmer%27s%20Guide" class="sharelink delicious" title="Bookmark this page in del.icio.us"></a></td> <td id="share-digg"><a href="http://digg.com/submit?phase=2&url=http%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html&title=Java%20Scripting%20Programmer%27s%20Guide" class="sharelink digg" title="Submit this page to Digg"></a></td> <td id="share-slashdot"><a href="http://slashdot.org/bookmark.pl?title=Java%20Scripting%20Programmer%27s%20Guide&url=http%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html" class="sharelink slashdot" title="Submit this page to Slashdot"></a></td> <td id="share-blank"> </td></tr></tbody></table></div></div></div> 38 39</td> 40</tr> 41</tbody></table> 42<!-- Body text begins here --> 43<ul> 44<li><span><a href="#who">Who is the Java Scripting API 45For?</a></span></li> 46<li><span><a href="#package">Scripting Package</a></span></li> 47<li><span><a href="#examples">Examples</a></span> 48<ul> 49<li><span><a href="#helloworld">"Hello, World"</a></span></li> 50<li><span><a href="#evalfile">Evaluating a Script 51File</a></span></li> 52<li><span><a href="#scriptvars">Script Variables</a></span></li> 53<li><span><a href="#invoke">Invoking Script Functions and 54Methods</a></span></li> 55<li><span><a href="#interfaces">Implementing Java Interfaces by 56Scripts</a></span></li> 57<li><span><a href="#scopes">Multiple Scopes for 58Scripts</a></span></li> 59</ul> 60</li> 61<li><span><a href="#jsengine">JavaScript Script 62Engine</a></span></li> 63<li><span><a href="#jstojava">JavaScript to Java 64Communication</a></span> 65<ul> 66<li><span><a href="#jsjavaclass">Accessing Java 67Classes</a></span></li> 68<li><span><a href="#jsimport">Importing Java Packages, 69Classes</a></span></li> 70<li><span><a href="#jsarrays">Creating, Converting and Using Java 71Arrays</a></span></li> 72<li><span><a href="#jsimplement">Implementing Java 73Interfaces</a></span></li> 74<li><span><a href="#jsextendabstract">Extending Abstract Java Classes 75</a></span></li> 76<li><span><a href="#jsextendconcrete">Extending Concrete Java Classes 77</a></span></li> 78<li><span><a href="#jsimplementmultiple">Implementing Multiple Java Interfaces 79</a></span></li> 80<li><span><a href="#classBoundImplementations">Class-Bound Implementations 81</a></span></li> 82<li><span><a href="#jsoverload">Overload Resolution</a></span></li> 83<li><span><a href="#dataTypeMapping">Mapping of Data Types Between Java 84and JavaScript</a></span></li> 85 86 87 88</ul> 89</li> 90<li><span><a href="#engineimpl">Implementing Your Own Script 91Engine</a></span></li> 92<li><span><a href="#refs">References</a></span></li> 93</ul> 94<span><a name="who" id="who"></a></span> 95<h2><span>Who is the Java Scripting API For?</span></h2> 96<span>Some useful characteristics of scripting languages 97are:</span> 98<ul> 99<li><span><b>Convenience</b>: Most scripting languages are 100dynamically typed. You can usually create new variables without 101declaring the variable type, and you can reuse variables to store 102objects of different types. Also, scripting languages tend to 103perform many type conversions automatically, for example, 104converting the number 10 to the text "10" as necessary.</span></li> 105<li><span><b>Developing rapid prototypes</b>: You can avoid the 106edit-compile-run cycle and just use edit-run!</span></li> 107<li><span><b>Application extension/customization</b>: You can 108"externalize" parts of your application - like configuration 109scripts, business logic/rules and math expressions for financial 110applications.</span></li> 111<li><span><b>"Command line" shells for applications</b> -for 112debugging, runtime/deploy time configuration etc. Most applications 113have a web-based GUI configuaration tool these days. But 114sysadmins/deployers frequently prefer command line tools. Instead 115of inventing ad-hoc scripting language for that purpose, a 116"standard" scripting language can be used.</span></li> 117</ul> 118<p><span>The Java<font size="-1"><sup>TM</sup></font> Scripting API 119is a scripting language indepedent framework for using script 120engines from Java code. With the Java Scripting API, it is possible 121to write customizable/extendable applications in the Java language 122and leave the customization scripting language choice to the end 123user. The Java application developer need not choose the extension 124language during development. If you write your application with 125JSR-223 API, then your users can use any JSR-223 compliant 126scripting language.</span></p> 127<hr> 128<span><a name="package" id="package"></a></span> 129<h2><span>Scripting Package</span></h2> 130<p><span>The Java Scripting functionality is in the <code><a href="http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html">javax.script</a></code> 131package. This is a relatively small, simple API. The starting point 132of the scripting API is the <code>ScriptEngineManager</code> class. 133A ScriptEngineManager object can discover script engines through 134the jar file service discovery mechanism. It can also instantiate 135ScriptEngine objects that interpret scripts written in a specific 136scripting language. The simplest way to use the scripting API is as 137follows:</span></p> 138<ol> 139<li><span>Create a <code>ScriptEngineManager</code> 140object.</span></li> 141<li><span>Get a <code>ScriptEngine</code> object from the 142manager.</span></li> 143<li><span>Evaluate script using the <code>ScriptEngine</code>'s 144<code>eval</code> methods.</span></li> 145</ol> 146<p><span>Now, it is time to look at some sample code. While it is 147not mandatory, it may be useful to know a bit of JavaScript to read 148these examples.</span></p> 149<hr> 150<span><a name="examples" id="examples"></a></span> 151<h2><span>Examples</span></h2> 152<span><a name="helloworld" id="helloworld"></a></span> 153<h3><span>"Hello, World"</span></h3> 154<p><span>From the <code>ScriptEngineManager</code> instance, we 155request a JavaScript engine instance using 156<code>getEngineByName</code> method. On the script engine, the 157<code>eval</code> method is called to execute a given String as 158JavaScript code! For brevity, in this as well as in subsequent 159examples, we have not shown exception handling. There are checked 160and runtime exceptions thrown from <code>javax.script</code> API. 161Needless to say, you have to handle the exceptions 162appropriately.</span></p> 163<pre> 164<span><code> 165// <a href="source/EvalScript.java">EvalScript.java</a> 166 167import javax.script.*; 168public class EvalScript { 169 public static void main(String[] args) throws Exception { 170 // create a script engine manager 171 <span class="classref">ScriptEngineManager</span> factory = new ScriptEngineManager(); 172 // create a JavaScript engine 173 <span class="classref">ScriptEngine</span> engine = factory.<span class="methodref">getEngineByName</span>("nashorn"); 174 // evaluate JavaScript code from String 175 engine.<span class="methodref">eval</span>("print('Hello, World')"); 176 } 177} 178</code></span> 179</pre> 180<hr> 181<a name="evalfile" id="evalfile"></a> 182<h3>Evaluating a Script File</h3> 183<p>In this example, we call the <code>eval</code> method that 184accepts <code>java.io.Reader</code> for the input source. The 185script read by the given reader is executed. This way it is 186possible to execute scripts from files, URLs and resources by 187wrapping the relevant input stream objects as readers.</p> 188<pre> 189<code> 190// <a href="source/EvalFile.java">EvalFile.java</a> 191 192import javax.script.*; 193 194public class EvalFile { 195 public static void main(String[] args) throws Exception { 196 // create a script engine manager 197 <span class="classref">ScriptEngineManager</span> factory = new ScriptEngineManager(); 198 // create JavaScript engine 199 <span class="classref">ScriptEngine</span> engine = factory.<span class="methodref">getEngineByName</span>("nashorn"); 200 // evaluate JavaScript code from given file - specified by first argument 201 engine.<span class="methodref">eval</span>(new java.io.FileReader(args[0])); 202 } 203} 204</code> 205</pre> 206Let us assume that we have the file named <a href="source/test.js">test.js</a> with the 207following text: 208<pre><code> 209print("This is hello from test.js"); 210</code> 211</pre> 212We can run the above Java as 213<pre><code> 214java EvalFile test.js 215</code> 216</pre> 217<hr> 218<a name="scriptvars" id="scriptvars"></a> 219<h3>Script Variables</h3> 220<p>When you embed script engines and scripts with your Java 221application, you may want to expose your application objects as 222global variables to scripts. This example demonstrates how you can 223expose your application objects as global variables to a script. We 224create a <code>java.io.File</code> in the application and expose 225the same as a global variable with the name "file". The script can 226access the variable - for example, it can call public methods on 227it. Note that the syntax to access Java objects, methods and fields 228is dependent on the scripting language. JavaScript supports the 229most "natural" Java-like syntax.</p> 230<p> 231Nashorn script engine pre-defines two global variables named "context" 232and "engine". The "context" variable is of type javax.script.ScriptContext 233and refers to the current ScriptContext instance passed to script engine's 234eval method. The "engine" variable is of type javax.script.ScriptEngine and 235refers to the current nashorn script engine instance evaluating the script. 236Both of these variables are non-writable, non-enumerable and non-configurable 237- which implies script code can not write overwrite the value, for..loop iteration 238on global object will not iterate these variables and these variables can not be 239deleted by script. 240<pre><code> 241// <a href="source/ScriptVars.java">ScriptVars.java</a> 242 243import javax.script.*; 244import java.io.*; 245 246public class ScriptVars { 247 public static void main(String[] args) throws Exception { 248 ScriptEngineManager manager = new ScriptEngineManager(); 249 ScriptEngine engine = manager.getEngineByName("nashorn"); 250 251 File f = new File("test.txt"); 252 // expose File object as variable to script 253 engine.<span class="methodref">put</span>("file", f); 254 255 // evaluate a script string. The script accesses "file" 256 // variable and calls method on it 257 engine.eval("print(file.getAbsolutePath())"); 258 } 259} 260 261</code> 262</pre> 263<hr> 264<a name="invoke" id="invoke"></a> 265<h3>Invoking Script Functions and Methods</h3> 266<p>Sometimes you may want to call a specific scripting function 267repeatedly - for example, your application menu functionality might 268be implemented by a script. In your menu's action event handler you 269may want to call a specific script function. The following example 270demonstrates invoking a specific script function from Java 271code.</p> 272<pre><code> 273// <a href="source/InvokeScriptFunction.java">InvokeScriptFunction.java</a> 274 275import javax.script.*; 276 277public class InvokeScriptFunction { 278 public static void main(String[] args) throws Exception { 279 ScriptEngineManager manager = new ScriptEngineManager(); 280 ScriptEngine engine = manager.getEngineByName("nashorn"); 281 282 // JavaScript code in a String 283 String script = "function hello(name) { print('Hello, ' + name); }"; 284 // evaluate script 285 engine.eval(script); 286 287 // <code>javax.script.Invocable</code> is an optional interface. 288 // Check whether your script engine implements it or not! 289 // Note that the JavaScript engine implements Invocable interface. 290 <span class="classref">Invocable</span> inv = (Invocable) engine; 291 292 // invoke the global function named "hello" 293 inv.<span class="methodref">invokeFunction</span>("hello", "Scripting!!" ); 294 } 295} 296 297</code> 298</pre> 299<p>If your scripting language is object based (like JavaScript) or 300object-oriented, then you can invoke a script method on a script 301object.</p> 302<pre><code> 303// <a href="source/InvokeScriptMethod.java">InvokeScriptMethod.java</a> 304 305import javax.script.*; 306 307public class InvokeScriptMethod { 308 public static void main(String[] args) throws Exception { 309 ScriptEngineManager manager = new ScriptEngineManager(); 310 ScriptEngine engine = manager.getEngineByName("nashorn"); 311 312 // JavaScript code in a String. This code defines a script object 'obj' 313 // with one method called 'hello'. 314 String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }"; 315 // evaluate script 316 engine.eval(script); 317 318 // <code>javax.script.Invocable</code> is an optional interface. 319 // Check whether your script engine implements or not! 320 // Note that the JavaScript engine implements Invocable interface. 321 <span class="classref">Invocable</span> inv = (Invocable) engine; 322 323 // get script object on which we want to call the method 324 Object obj = engine.<span class="methodref">get</span>("obj"); 325 326 // invoke the method named "hello" on the script object "obj" 327 inv.<span class="methodref">invokeMethod</span>(obj, "hello", "Script Method !!" ); 328 } 329} 330 331</code> 332</pre> 333<hr> 334<a name="interfaces" id="interfaces"></a> 335<h3>Implementing Java Interfaces by Scripts</h3> 336<p>Instead of calling specific script functions from Java, 337sometimes it is convenient to implement a Java interface by script 338functions or methods. Also, by using interfaces we can avoid having 339to use the <code>javax.script</code> API in many places. We can get 340an interface implementor object and pass it to various Java APIs. 341The following example demonstrates implementing the 342<code>java.lang.Runnable</code> interface with a script.</p> 343<pre><code> 344// <a href="source/RunnableImpl.java">RunnableImpl.java</a> 345 346import javax.script.*; 347 348public class RunnableImpl { 349 public static void main(String[] args) throws Exception { 350 ScriptEngineManager manager = new ScriptEngineManager(); 351 ScriptEngine engine = manager.getEngineByName("nashorn"); 352 353 // JavaScript code in a String 354 String script = "function run() { print('run called'); }"; 355 356 // evaluate script 357 engine.eval(script); 358 359 <span class="classref">Invocable</span> inv = (Invocable) engine; 360 361 // get Runnable interface object from engine. This interface methods 362 // are implemented by script functions with the matching name. 363 Runnable r = inv.<span class="methodref">getInterface</span>(Runnable.class); 364 365 // start a new thread that runs the script implemented 366 // runnable interface 367 Thread th = new Thread(r); 368 th.start(); 369 th.join(); 370 } 371} 372</code> 373</pre> 374<p>If your scripting language is object-based or object-oriented, 375it is possible to implement a Java interface by script methods on 376script objects. This avoids having to call script global functions 377for interface methods. The script object can store the "state" 378associated with the interface implementor.</p> 379<pre><code> 380// <a href="source/RunnableImplObject.java">RunnableImplObject.java</a> 381 382import javax.script.*; 383 384public class RunnableImplObject { 385 public static void main(String[] args) throws Exception { 386 ScriptEngineManager manager = new ScriptEngineManager(); 387 ScriptEngine engine = manager.getEngineByName("nashorn"); 388 389 // JavaScript code in a String 390 String script = "var obj = new Object(); obj.run = function() { print('run method called'); }"; 391 392 // evaluate script 393 engine.eval(script); 394 395 // get script object on which we want to implement the interface with 396 Object obj = engine.<span class="methodref">get</span>("obj"); 397 398 <span class="classref">Invocable</span> inv = (Invocable) engine; 399 400 // get Runnable interface object from engine. This interface methods 401 // are implemented by script methods of object 'obj' 402 Runnable r = inv.<span class="methodref">getInterface</span>(obj, Runnable.class); 403 404 // start a new thread that runs the script implemented 405 // runnable interface 406 Thread th = new Thread(r); 407 th.start(); 408 th.join(); 409 } 410} 411</code> 412</pre> 413<hr> 414<a name="scopes" id="scopes"></a> 415<h3>Multiple Scopes for Scripts</h3> 416<p>In the <a href="#scriptvars">script variables</a> example, we 417saw how to expose application objects as script global variables. 418It is possible to expose multiple global "scopes" for scripts. A 419single scope is an instance of <code>javax.script.Bindings</code>. 420This interface is derived from <code>java.util.Map<String, 421Object></code>. A scope a set of name-value pairs where name is 422any non-empty, non-null String. 423<code>javax.script.ScriptContext</code> interface supports multiple 424scopes with associated Bindings for each 425scope. By default, every script engine has a default script 426context. The default script context has atleast one scope called 427"ENGINE_SCOPE". Various scopes supported by a script context are 428available through <code>getScopes</code> method.</p> 429<pre><code> 430// <a href="source/MultiScopes.java">MultiScopes.java</a> 431 432import javax.script.*; 433 434public class MultiScopes { 435 public static void main(String[] args) throws Exception { 436 ScriptEngineManager manager = new ScriptEngineManager(); 437 ScriptEngine engine = manager.getEngineByName("nashorn"); 438 439 engine.put("x", "hello"); 440 // print global variable "x" 441 engine.eval("print(x);"); 442 // the above line prints "hello" 443 444 // Now, pass a different script context 445 <span class="classref">ScriptContext</span> newContext = new <span class="classref">SimpleScriptContext</span>(); 446 newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); 447 <span class="classref">Bindings</span> engineScope = newContext.<span class="methodref">getBindings</span>(ScriptContext.ENGINE_SCOPE); 448 449 // add new variable "x" to the new engineScope 450 engineScope.<span class="methodref">put</span>("x", "world"); 451 452 // execute the same script - but this time pass a different script context 453 engine.eval("print(x);", newContext); 454 // the above line prints "world" 455 } 456} 457 458</code> 459</pre> 460<hr> 461<a name="jsengine" id="jsengine"></a> 462<h2>JavaScript Script Engine</h2> 463<p>Oracle's implementation of JDK 8 is co-bundled with the Nashorn ECMAScript 464script engine. 465<hr> 466<a name="jstojava" id="jstojava"></a> 467<h2>JavaScript to Java Communication</h2> 468<p>For the most part, accessing Java classes, objects and methods 469is straightforward. In particular field and method access from 470JavaScript is the same as it is from Java. We highlight important 471aspects of JavaScript Java access here. 472The following examples are JavaScript snippets accessing Java. This 473section requires knowledge of JavaScript. This section can be 474skipped if you are planning to use some other JSR-223 scripting 475language rather than JavaScript.</p> 476<hr> 477<a name="jsjavaclass" id=jsjavalass"></a> 478<h3>Accessing Java Classes</h3> 479<pre> 480<code> 481// <a href="source/javatypes.js">javatypes.js</a> 482 483 var arrayListType = Java.type("java.util.ArrayList") 484 var intType = Java.type("int") 485 var stringArrayType = Java.type("java.lang.String[]") 486 var int2DArrayType = Java.type("int[][]") 487</code> 488</pre> 489 490Note that the name of the type is always a string for a fully qualified name. You can use any of these expressions to create new instances, e.g.: 491 492<pre><code> 493 var anArrayList = new (Java.type("java.util.ArrayList")) 494</code></pre> 495 496or 497 498<pre><code> 499 var ArrayList = Java.type("java.util.ArrayList") 500 var anArrayList = new ArrayList 501 var anArrayListWithSize = new ArrayList(16) 502</code></pre> 503 504In the special case of inner classes, you can either use the JVM fully qualified name, meaning using the dollar sign in the class name, or you can use the dot: 505 506<pre><code> 507 var ftype = Java.type("java.awt.geom.Arc2D$Float") 508</code></pre> 509 510and 511 512<pre><code> 513 var ftype = Java.type("java.awt.geom.Arc2D.Float") 514</code></pre> 515 516both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An alternative way to access the inner class is as a property of the outer class: 517 518<pre><code> 519 var arctype = Java.type("java.awt.geom.Arc2D") 520 var ftype = arctype.Float 521</code></pre> 522<p> 523You can access both static and non-static inner classes. If you want to create an instance of a non-static inner class, remember to pass an instance of its outer class as the first argument to the constructor. 524</p> 525<p> 526In addition to creating new instances, the type objects returned from <code>Java.type</code> calls can also be used to access the 527static fields and methods of the classes: 528<pre><code> 529 var File = Java.type("java.io.File") 530 File.createTempFile("nashorn", ".tmp") 531</code></pre> 532<p> 533Methods with names of the form <code>isXxx()</code>, <code>getXxx()</code>, and <code>setXxx()</code> can also be used as properties, for both instances and statics. 534</p> 535<p> 536A type object returned from <code>Java.type</code> is distinct from a <code>java.lang.Class</code> object. You can obtain one from the other using properties <code>class</code> and <code>static</code> on them. 537<pre><code> 538 var ArrayList = Java.type("java.util.ArrayList") 539 var a = new ArrayList 540 541 // All of the following print true: 542 print("Type acts as target of instanceof: " + (a instanceof ArrayList)) 543 print("Class doesn't act as target of instanceof: " + !(a instanceof a.getClass())) 544 print("Type is not same as instance's getClass(): " + (a.getClass() !== ArrayList)) 545 print("Type's `class` property is same as instance getClass(): " + (a.getClass() === ArrayList.class)) 546 print("Type is same as instance getClass()'s `static` property: " + (a.getClass().static === ArrayList)) 547</code></pre> 548<p> 549You can think of the type object as similar to the class names as used in Java source code: you use them as the 550arguments to the <code>new</code> and <code>instanceof</code> operators and as the namespace for the static fields 551and methods, but they are different than the runtime <code>Class</code> objects returned by <code>getClass()</code> calls. 552Syntactically and semantically, this separation produces code that is most similar to Java code, where a distinction 553between compile-time class expressions and runtime class objects also exists. (Also, Java can't have the equivalent of <code>static</code> 554property on a <code>Class</code> object since compile-time class expressions are never reified as objects). 555</p> 556<hr> 557<a name="jsimport" id="jsimport"></a> 558<h3>Importing Java Packages, Classes</h3> 559<p>The built-in functions <code>importPackage</code> (in compatibility script) and 560<code>importClass</code> can be used to import Java packages and 561classes.</p> 562<pre><code> 563 564// <a href="source/importpackageclass.js">importpackageclass.js</a> 565 566// load compatibility script 567load("nashorn:mozilla_compat.js"); 568// Import Java packages and classes 569// like import package.*; in Java 570<span class="functionref">importPackage</span>(java.awt); 571// like import java.awt.Frame in Java 572<span class="functionref">importClass</span>(java.awt.Frame); 573// Create Java Objects by "new ClassName" 574var frame = new java.awt.Frame("hello"); 575// Call Java public methods from script 576frame.setVisible(true); 577// Access "JavaBean" properties like "fields" 578print(frame.title); 579</code> 580</pre> 581<p>The <span class="objectref">Packages</span> global variable can 582be used to access Java packages. Examples: 583<code>Packages.java.util.Vector</code>, 584<code>Packages.javax.swing.JFrame</code>. Please note that "java" 585is a shortcut for "Packages.java". There are equivalent shortcuts 586for javax, org, edu, com, net prefixes, so pratically all JDK 587platform classes can be accessed without the "Packages" prefix.</p> 588<p>Note that java.lang is not imported by default (unlike Java) 589because that would result in conflicts with JavaScript's built-in 590Object, Boolean, Math and so on.</p> 591<p><code>importPackage</code> and <code>importClass</code> 592functions "pollute" the global variable scope of JavaScript. To 593avoid that, you may use <span class="functionref">JavaImporter</span>.</p> 594<pre><code> 595 596// <a href="source/javaimporter.js">javaimporter.js</a> 597 598// create JavaImporter with specific packages and classes to import 599 600var SwingGui = new <span class="functionref">JavaImporter</span>(javax.swing, 601 javax.swing.event, 602 javax.swing.border, 603 java.awt.event); 604with (SwingGui) { 605 // within this 'with' statement, we can access Swing and AWT 606 // classes by unqualified (simple) names. 607 608 var mybutton = new JButton("test"); 609 var myframe = new JFrame("test"); 610} 611 612</code> 613</pre> 614<hr> 615<a name="jsarrays" id="jsarrays"></a> 616<h3>Creating, Converting and Using Java Arrays</h3> 617<p> 618Array element access or length access is the same as in Java.</p> 619<pre><code> 620// <a href="source/javaarray.js">javaarray.js</a> 621 622// create Java String array of 5 elements 623var StringArray = Java.type("java.lang.String[]"); 624var a = new StringArray(5); 625 626// Accessing elements and length access is by usual Java syntax 627a[0] = "scripting is great!"; 628print(a.length); 629print(a[0]); 630</code> 631</pre> 632<p> 633It is also possible to convert between JavaScript and Java arrays. 634Given a JavaScript array and a Java type, <code>Java.to</code> returns a Java array with the same initial contents, and with the specified array type. 635</p> 636<pre><code> 637 var anArray = [1, "13", false] 638 var javaIntArray = Java.to(anArray, "int[]") 639 print(javaIntArray[0]) // prints 1 640 print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion 641 print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion 642</code></pre> 643<p> 644You can use either a string or a type object returned from <code>Java.type()</code> to specify the type of the array. 645You can also omit the array type, in which case a <code>Object[]</code> will be created. 646</p> 647<p> 648Given a Java array or Collection, <code>Java.from</code> returns a JavaScript array with a shallow copy of its contents. Note that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will want to use this method. 649</p> 650<pre><code> 651var File = Java.type("java.io.File"); 652var listCurDir = new File(".").listFiles(); 653var jsList = Java.from(listCurDir); 654print(jsList); 655</code></pre> 656<hr> 657<a name="jsimplement" id="jsimplement"></a> 658<h3>Implementing Java interfaces</h3> 659<p>A Java interface can be implemented in JavaScript by using a 660Java anonymous class-like syntax:</p> 661<pre><code> 662// <a href="source/runnable.js">runnable.js</a> 663 664var r = new java.lang.Runnable() { 665 run: function() { 666 print("running...\n"); 667 } 668}; 669 670// "r" can be passed to Java methods that expect java.lang.Runnable 671var th = new java.lang.Thread(r); 672th.start(); 673th.join(); 674</code> 675</pre> 676<p>When an interface with a single method is expected, you can pass 677a script function directly.(auto conversion)</p> 678<pre><code> 679// <a href="source/samfunc.js">samfunc.js</a> 680 681function func() { 682 print("I am func!"); 683} 684 685// pass script function for java.lang.Runnable argument 686var th = new java.lang.Thread(func); 687th.start(); 688th.join(); 689</code> 690</pre> 691<hr> 692<a name="jsextendabstract" id="jsextendabstract"></a> 693<h3>Extending Abstract Java Classes</h3> 694<p> 695If a Java class is abstract, you can instantiate an anonymous subclass of it using an argument list that is applicable to any of its public or protected constructors, but inserting a JavaScript object with functions properties that provide JavaScript implementations of the abstract methods. If method names are overloaded, the JavaScript function will provide implementation for all overloads. E.g.: 696</p> 697 698<pre><code> 699 var TimerTask = Java.type("java.util.TimerTask") 700 var task = new TimerTask({ run: function() { print("Hello World!") } }) 701</code></pre> 702 703Nashorn supports a syntactic extension where a "new" expression followed by an argument is identical to invoking the constructor and passing the argument to it, so you can write the above example also as: 704 705<pre><code> 706 var task = new TimerTask { 707 run: function() { 708 print("Hello World!") 709 } 710 } 711</code></pre> 712 713which is very similar to Java anonymous inner class definition. On the other hand, if the type is an abstract type with a single abstract method (commonly referred to as a "SAM type") or all abstract methods it has share the same overloaded name), then instead of an object, you can just pass a function, so the above example can become even more simplified to: 714 715<pre><code> 716 var task = new TimerTask(function() { print("Hello World!") }) 717</code></pre> 718 719<p> 720Note that in every one of these cases if you are trying to instantiate an abstract class that has constructors that take some arguments, you can invoke those simply by specifying the arguments after the initial implementation object or function. 721</p> 722<p> 723The use of functions can be taken even further; if you are invoking a Java method that takes a SAM type, you can just pass in a function object, and Nashorn will know what you meant: 724</p> 725<code><pre> 726 Java.type("java.util.Timer") 727 timer.schedule(function() { print("Hello World!") }) 728</code></pre> 729 730Here, <code>Timer.schedule()</code> expects a <code>TimerTask</code> as its argument, so Nashorn creates an instance of a TimerTask subclass and uses the passed function to implement its only abstract method, run(). In this usage though, you can't use non-default constructors; the type must be either an interface, or must have a protected or public no-arg constructor. 731 732<hr> 733<a name="jsextendconcrete" id="jsextendconcrete"></a> 734<h3>Extending Concrete Java Classes</h3> 735<p> 736To extend a concrete Java class, you have to use <code>Java.extend</code> function. 737<code>Java.extend</code> returns a type object for a subclass of the specified Java class (or implementation of the specified interface) that acts as a script-to-Java adapter for it. 738</p> 739<pre><code> 740// <a href="source/javaextend.js">javaextend.js</a> 741 742var ArrayList = Java.type("java.util.ArrayList") 743var ArrayListExtender = Java.extend(ArrayList) 744var printSizeInvokedArrayList = new ArrayListExtender() { 745 size: function() { print("size invoked!"); } 746} 747var printAddInvokedArrayList = new ArrayListExtender() { 748 add: function(x, y) { 749 if(typeof(y) === "undefined") { 750 print("add(e) invoked!"); 751 } else { 752 print("add(i, e) invoked!"); 753 } 754 } 755}; 756printSizeInvokedArrayList.size(); 757printAddInvokedArrayList.add(33, 33); 758</code></pre> 759<p> 760The reason you must use <code>Java.extend()</code> with concrete classes is that with concrete classes, there can be a 761syntactic ambiguity if you just invoke their constructor. Consider this example: 762</p> 763<pre><code> 764var t = new java.lang.Thread({ run: function() { print("Hello!") } }) 765</code></pre> 766<p> 767If we allowed subclassing of concrete classes with constructor syntax, Nashorn couldn't tell if you're creating a new 768<code>Thread</code> and passing it a <code>Runnable</code> at this point, or you are subclassing <code>Thread</code> and 769passing it a new implementation for its own <code>run()</code> method. 770</p> 771<hr> 772<a name="jsimplementmultiple" id="jsimplementmultiple"></a> 773<h3>Implementing Multiple Interfaces</h3> 774<p> 775<code>Java.extend</code> can in fact take a list of multiple types. At most one of the types can be a class, and the rest must 776be interfaces (the class doesn't have to be the first in the list). You will get back an object that extends the class and 777implements all the interfaces. (Obviously, if you only specify interfaces and no class, the object will extend <code>java.lang.Object</code>). 778<hr> 779<a name="classBoundImplementations" id="classBoundImplementations"></a> 780<h3>Class-Bound Implementations</h3> 781<p> 782The methods shown so far for extending Java classes and implementing interfaces – passing an implementation JavaScript object 783or function to a constructor, or using <code>Java.extend</code> with <code>new</code> – all produce classes that take an 784extra JavaScript object parameter in their constructors that specifies the implementation. The implementation is therefore always bound 785to the actual instance being created with <code>new</code>, and not to the whole class. This has some advantages, for example in the 786memory footprint of the runtime, as Nashorn can just create a single "universal adapter" for every combination of types being implemented. 787In reality, the below code shows that different instantiations of, say, <code>Runnable</code> have the same class regardless of them having 788different JavaScript implementation objects: 789</p> 790<pre><code> 791var Runnable = java.lang.Runnable; 792var r1 = new Runnable(function() { print("I'm runnable 1!") }) 793var r2 = new Runnable(function() { print("I'm runnable 2!") }) 794r1.run() 795r2.run() 796print("We share the same class: " + (r1.class === r2.class)) 797</code></pre> 798<p> 799prints: 800</p> 801<pre><code> 802I'm runnable 1! 803I'm runnable 2! 804We share the same class: true 805</code></pre> 806<p> 807Sometimes, however, you'll want to extend a Java class or implement an interface with implementation bound to the class, not to 808its instances. Such a need arises, for example, when you need to pass the class for instantiation to an external API; prime example 809of this is the JavaFX framework where you need to pass an Application class to the FX API and let it instantiate it. 810</p> 811<p> 812Fortunately, there's a solution for that: <code>Java.extend()</code> – aside from being able to take any number of type parameters 813denoting a class to extend and interfaces to implement – can also take one last argument that has to be a JavaScript object 814that serves as the implementation for the methods. In this case, <code>Java.extend()</code> will create a class that has the same 815constructors as the original class had, as they don't need to take an an extra implementation object parameter. The example below 816shows how you can create class-bound implementations, and shows that in this case, the implementation classes for different invocations 817are indeed different: 818</p> 819<pre><code> 820var RunnableImpl1 = Java.extend(java.lang.Runnable, function() { print("I'm runnable 1!") }) 821var RunnableImpl2 = Java.extend(java.lang.Runnable, function() { print("I'm runnable 2!") }) 822var r1 = new RunnableImpl1() 823var r2 = new RunnableImpl2() 824r1.run() 825r2.run() 826print("We share the same class: " + (r1.class === r2.class)) 827</code></pre> 828<p> 829prints: 830</p> 831<pre><code> 832I'm runnable 1! 833I'm runnable 2! 834We share the same class: false 835</code></pre> 836<p> 837As you can see, the major difference here is that we moved the implementation object into the invocation of <code>Java.extend</code> 838from the constructor invocations – indeed the constructor invocations now don't even need to take an extra parameter! Since 839the implementations are bound to a class, the two classes obviously can't be the same, and we indeed see that the two runnables no 840longer share the same class – every invocation of <code>Java.extend()</code> with a class-specific implementation object triggers 841the creation of a new Java adapter class. 842</p> 843<p> 844Finally, the adapter classes with class-bound implementations can <i>still</i> take an additional constructor parameter to further 845override the behavior on a per-instance basis. Thus, you can even combine the two approaches: you can provide part of the implementation 846in a class-based JavaScript implementation object passed to <code>Java.extend</code>, and part in another object passed to the constructor. 847Whatever functions are provided by the constructor-passed object will override the functions in the class-bound object. 848</p> 849<pre><code> 850var RunnableImpl = Java.extend(java.lang.Runnable, function() { print("I'm runnable 1!") }) 851var r1 = new RunnableImpl() 852var r2 = new RunnableImpl(function() { print("I'm runnable 2!") }) 853r1.run() 854r2.run() 855print("We share the same class: " + (r1.class === r2.class)) 856</code></pre> 857<p> 858prints: 859</p> 860<pre><code> 861I'm runnable 1! 862I'm runnable 2! 863We share the same class: true 864</code></pre> 865<hr> 866<a name="jsoverload" id="jsoverload"></a> 867<h3>Overload Resolution</h3> 868<p>Java methods can be overloaded by argument types. In Java, 869overload resolution occurs at compile time (performed by javac). 870When calling Java methods from Nashorn, the appropriate method will be 871selected based on the argument types at invocation time. You do not need 872to do anything special – the correct Java method overload variant 873is selected based automatically. You still have the option of explicitly 874specifying a particular overload variant. Reasons for this include 875either running into a genuine ambiguity with actual argument types, or 876rarely reasons of performance – if you specify the actual overload 877then the engine doesn't have to perform resolution during invocation. 878Individual overloads of a Java methods are exposed as special properties 879with the name of the method followed with its signature in parentheses. 880You can invoke them like this:</p> 881<pre><code> 882// <a href="source/overload.js">overload.js</a> 883 884var out = java.lang.System.out; 885 886// select a particular print function 887out["println(Object)"]("hello"); 888</code> 889</pre> 890<p> 891Note that you normally don't even have to use qualified class names in 892the signatures as long as the unqualified name of the type is sufficient 893for uniquely identifying the signature. In practice this means that only 894in the extremely unlikely case that two overloads only differ in 895parameter types that have identical unqualified names but come from 896different packages would you need to use the fully qualified name of the 897class. 898</p> 899<hr> 900<a name="dataTypeMapping" id="dataTypeMapping"></a> 901<h3>Mapping of Data Types Between Java and JavaScript</h3> 902<p> 903We have previously shown some of the data type mappings between Java and JavaScript. 904We saw that arrays need to be explicitly converted. We have also shown that JavaScript functions 905are automatically converted to SAM types when passed as parameters to Java methods. Most other 906conversions work as you would expect. 907</p> 908<p> 909Every JavaScript object is also a <code>java.util.Map</code> so APIs receiving maps will receive them directly. 910</p> 911<p> 912When numbers are passed to a Java API, they will be converted to the expected target numeric type, either boxed or 913primitive, but if the target type is less specific, say <code>Number</code> or <code>Object</code>, you can only 914count on them being a <code>Number</code>, and have to test specifically for whether it's a boxed <code>Double</code>, 915<code>Integer</code>, <code>Long</code>, etc. – it can be any of these due to internal optimizations. Also, you 916can pass any JavaScript value to a Java API expecting either a boxed or primitive number; the JavaScript specification's 917<code>ToNumber</code> conversion algorithm will be applied to the value. 918</p> 919<p> 920In a similar vein, if a Java method expects a <code>String</code> or a <code>Boolean</code>, the values will be 921converted using all conversions allowed by the JavaScript specification's <code>ToString</code> and <code>ToBoolean</code> 922conversions. 923</p> 924<p> 925Finally, a word of caution about strings. Due to internal performance optimizations of string operations, JavaScript strings are 926not always necessarily of type <code>java.lang.String</code>, but they will always be of type <code>java.lang.CharSequence</code>. 927If you pass them to a Java method that expects a <code>java.lang.String</code> parameter, then you will naturally receive a Java 928String, but if the signature of your method is more generic, i.e. it receives a <code>java.lang.Object</code> parameter, you can 929end up with an object of private engine implementation class that implements <code>CharSequence</code> but is not a Java String. 930</p> 931<hr> 932<a name="engineimpl" id="engineimpl"></a> 933<h2>Implementing Your Own Script Engine</h2> 934<p>We will not cover implementation of JSR-223 compliant script 935engines in detail. Minimally, you need to implement the 936<code>javax.script.ScriptEngine</code> and 937<code>javax.script.ScriptEngineFactory</code> interfaces. The 938abstract class <code>javax.script.AbstractScriptEngine</code> 939provides useful defaults for a few methods of the 940<code>ScriptEngine</code> interface.</p> 941<p>Before starting to implement a JSR-223 engine, you may want to 942check <a href="http://java.net/projects/Scripting">http://java.net/projects/Scripting</a> 943project. This project maintains JSR-223 implementations for many 944popular open source scripting languages.</p> 945<hr> 946<a name="refs" id="refs"></a> 947<h2>References</h2> 948<ul> 949<li><a href="http://jcp.org/en/jsr/detail?id=223">JSR-223 Scripting 950for the Java Platform</a></li> 951<li><a href="http://java.net/projects/Scripting">http://java.net/projects/Scripting 952</a></li> 953</ul> 954 955 956 957<div class="hr"><hr></div> 958<table summary="layout" border="0" width="100%"> 959<tbody><tr valign="TOP"> 960<td width="30%"> <img src="Java%20Scripting%20Programmer%27s%20Guide_files/logo_oracle_footer.gif" alt="Oracle and/or its affiliates" border="0" height="29" width="100"><br> 961<font size="+1"> <i>Java Technology</i></font> </td> 962 963<td width="30%"> 964<p><font size="-2"> 965<a href="http://docs.oracle.com/javase/6/docs/legal/cpyr.html">Copyright �</a> 2013, Oracle and/or its affiliates. All rights reserved. 966</font></p> 967</td> 968<td width="30%"> 969<p align="right"><font size="-2"><a href="http://download.oracle.com/javase/feedback.html">Contact Us</a></font></p><font size="-2"> 970</font></td> 971</tr> 972</tbody></table> 973<div class="hr"><hr></div> 974</div> 975 976<!-- Start SiteCatalyst code --> 977<script language="JavaScript" src="Java%20Scripting%20Programmer%27s%20Guide_files/s_code_download.js"></script> 978<script language="JavaScript" src="Java%20Scripting%20Programmer%27s%20Guide_files/s_code.js"></script> 979 980<!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** --> 981<!-- Below code will send the info to Omniture server --> 982<script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script> 983 984<!-- End SiteCatalyst code --> 985 986 987 988</body></html> 989