aboutsummaryrefslogtreecommitdiff
path: root/docs/JavaScriptingProgrammersGuide.html
blob: 811b29c9d513977586d805c59fae22ca2e3e5eb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
<!--
 Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.

 This code is free software; you can redistribute it and/or modify it
 under the terms of the GNU General Public License version 2 only, as
 published by the Free Software Foundation.  Oracle designates this
 particular file as subject to the "Classpath" exception as provided
 by Oracle in the LICENSE file that accompanied this code.

 This code is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 version 2 for more details (a copy is included in the LICENSE file that
 accompanied this code).

 You should have received a copy of the GNU General Public License version
 2 along with this work; if not, write to the Free Software Foundation,
 Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

 Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 or visit www.oracle.com if you need additional information or have any
 questions.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html class=" regenabled  gecko radius jsenabled regloaded" xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Java Scripting Programmer's Guide</title>

<!-- ============ -->
<!-- MAIN CONTENT -->
<!-- ============ -->
<table summary="layout" border="0" width="100%">
<tbody><tr>
<td>

<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&amp;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&amp;url=http%3A%2F%2Fdocs.oracle.com%2Fjavase%2F6%2Fdocs%2Ftechnotes%2Fguides%2Fscripting%2Fprogrammer_guide%2Findex.html&amp;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&amp;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>

</td>
</tr>
</tbody></table>
<!-- Body text begins here -->
<ul>
<li><span><a href="#who">Who is the Java Scripting API
For?</a></span></li>
<li><span><a href="#package">Scripting Package</a></span></li>
<li><span><a href="#examples">Examples</a></span>
<ul>
<li><span><a href="#helloworld">"Hello, World"</a></span></li>
<li><span><a href="#evalfile">Evaluating a Script
File</a></span></li>
<li><span><a href="#scriptvars">Script Variables</a></span></li>
<li><span><a href="#invoke">Invoking Script Functions and
Methods</a></span></li>
<li><span><a href="#interfaces">Implementing Java Interfaces by
Scripts</a></span></li>
<li><span><a href="#scopes">Multiple Scopes for
Scripts</a></span></li>
</ul>
</li>
<li><span><a href="#jsengine">JavaScript Script
Engine</a></span></li>
<li><span><a href="#jstojava">JavaScript to Java
Communication</a></span>
<ul>
<li><span><a href="#jsjavaclass">Accessing Java
Classes</a></span></li>
<li><span><a href="#jsimport">Importing Java Packages,
Classes</a></span></li>
<li><span><a href="#jsarrays">Creating, Converting and Using Java
Arrays</a></span></li>
<li><span><a href="#jsimplement">Implementing Java
Interfaces</a></span></li>
<li><span><a href="#jsextend">Extending Java classes
</a></span></li>
<li><span><a href="#jsoverload">Overload Resolution</a></span></li>
</ul>
</li>
<li><span><a href="#engineimpl">Implementing Your Own Script
Engine</a></span></li>
<li><span><a href="#refs">References</a></span></li>
</ul>
<span><a name="who" id="who"></a></span>
<h2><span>Who is the Java Scripting API For?</span></h2>
<span>Some useful characteristics of scripting languages
are:</span>
<ul>
<li><span><b>Convenience</b>: Most scripting languages are
dynamically typed. You can usually create new variables without
declaring the variable type, and you can reuse variables to store
objects of different types. Also, scripting languages tend to
perform many type conversions automatically, for example,
converting the number 10 to the text "10" as necessary.</span></li>
<li><span><b>Developing rapid prototypes</b>: You can avoid the
edit-compile-run cycle and just use edit-run!</span></li>
<li><span><b>Application extension/customization</b>: You can
"externalize" parts of your application - like configuration
scripts, business logic/rules and math expressions for financial
applications.</span></li>
<li><span><b>"Command line" shells for applications</b> -for
debugging, runtime/deploy time configuration etc. Most applications
have a web-based GUI configuaration tool these days. But
sysadmins/deployers frequently prefer command line tools. Instead
of inventing ad-hoc scripting language for that purpose, a
"standard" scripting language can be used.</span></li>
</ul>
<p><span>The Java<font size="-1"><sup>TM</sup></font> Scripting API
is a scripting language indepedent framework for using script
engines from Java code. With the Java Scripting API, it is possible
to write customizable/extendable applications in the Java language
and leave the customization scripting language choice to the end
user. The Java application developer need not choose the extension
language during development. If you write your application with
JSR-223 API, then your users can use any JSR-223 compliant
scripting language.</span></p>
<hr>
<span><a name="package" id="package"></a></span>
<h2><span>Scripting Package</span></h2>
<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>
package. This is a relatively small, simple API. The starting point
of the scripting API is the <code>ScriptEngineManager</code> class.
A ScriptEngineManager object can discover script engines through
the jar file service discovery mechanism. It can also instantiate
ScriptEngine objects that interpret scripts written in a specific
scripting language. The simplest way to use the scripting API is as
follows:</span></p>
<ol>
<li><span>Create a <code>ScriptEngineManager</code>
object.</span></li>
<li><span>Get a <code>ScriptEngine</code> object from the
manager.</span></li>
<li><span>Evaluate script using the <code>ScriptEngine</code>'s
<code>eval</code> methods.</span></li>
</ol>
<p><span>Now, it is time to look at some sample code. While it is
not mandatory, it may be useful to know a bit of JavaScript to read
these examples.</span></p>
<hr>
<span><a name="examples" id="examples"></a></span>
<h2><span>Examples</span></h2>
<span><a name="helloworld" id="helloworld"></a></span>
<h3><span>"Hello, World"</span></h3>
<p><span>From the <code>ScriptEngineManager</code> instance, we
request a JavaScript engine instance using
<code>getEngineByName</code> method. On the script engine, the
<code>eval</code> method is called to execute a given String as
JavaScript code! For brevity, in this as well as in subsequent
examples, we have not shown exception handling. There are checked
and runtime exceptions thrown from <code>javax.script</code> API.
Needless to say, you have to handle the exceptions
appropriately.</span></p>
<pre>
<span><code>
// <a href="source/EvalScript.java">EvalScript.java</a>

import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        <span class="classref">ScriptEngineManager</span> factory = new ScriptEngineManager();
        // create a JavaScript engine
        <span class="classref">ScriptEngine</span> engine = factory.<span class="methodref">getEngineByName</span>("nashorn");
        // evaluate JavaScript code from String
        engine.<span class="methodref">eval</span>("print('Hello, World')");
    }
}
</code></span>
</pre>
<hr>
<a name="evalfile" id="evalfile"></a>
<h3>Evaluating a Script File</h3>
<p>In this example, we call the <code>eval</code> method that
accepts <code>java.io.Reader</code> for the input source. The
script read by the given reader is executed. This way it is
possible to execute scripts from files, URLs and resources by
wrapping the relevant input stream objects as readers.</p>
<pre>
<code>
// <a href="source/EvalFile.java">EvalFile.java</a>

import javax.script.*;

public class EvalFile {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        <span class="classref">ScriptEngineManager</span> factory = new ScriptEngineManager();
        // create JavaScript engine
        <span class="classref">ScriptEngine</span> engine = factory.<span class="methodref">getEngineByName</span>("nashorn");
        // evaluate JavaScript code from given file - specified by first argument
        engine.<span class="methodref">eval</span>(new java.io.FileReader(args[0]));
    }
}
</code>
</pre>
Let us assume that we have the file named <a href="source/test.js">test.js</a> with the
following text:
<pre><code>
print("This is hello from test.js");
</code>
</pre>
We can run the above Java as
<pre><code>
java EvalFile test.js
</code>
</pre>
<hr>
<a name="scriptvars" id="scriptvars"></a>
<h3>Script Variables</h3>
<p>When you embed script engines and scripts with your Java
application, you may want to expose your application objects as
global variables to scripts. This example demonstrates how you can
expose your application objects as global variables to a script. We
create a <code>java.io.File</code> in the application and expose
the same as a global variable with the name "file". The script can
access the variable - for example, it can call public methods on
it. Note that the syntax to access Java objects, methods and fields
is dependent on the scripting language. JavaScript supports the
most "natural" Java-like syntax.</p>
<pre><code>
// <a href="source/ScriptVars.java">ScriptVars.java</a>

import javax.script.*;
import java.io.*;

public class ScriptVars { 
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        File f = new File("test.txt");
        // expose File object as variable to script
        engine.<span class="methodref">put</span>("file", f);

        // evaluate a script string. The script accesses "file" 
        // variable and calls method on it
        engine.eval("print(file.getAbsolutePath())");
    }
}

</code>
</pre>
<hr>
<a name="invoke" id="invoke"></a>
<h3>Invoking Script Functions and Methods</h3>
<p>Sometimes you may want to call a specific scripting function
repeatedly - for example, your application menu functionality might
be implemented by a script. In your menu's action event handler you
may want to call a specific script function. The following example
demonstrates invoking a specific script function from Java
code.</p>
<pre><code>
// <a href="source/InvokeScriptFunction.java">InvokeScriptFunction.java</a>

import javax.script.*;

public class InvokeScriptFunction {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        // JavaScript code in a String
        String script = "function hello(name) { print('Hello, ' + name); }";
        // evaluate script
        engine.eval(script);

        // <code>javax.script.Invocable</code> is an optional interface.
        // Check whether your script engine implements it or not!
        // Note that the JavaScript engine implements Invocable interface.
        <span class="classref">Invocable</span> inv = (Invocable) engine;

        // invoke the global function named "hello"
        inv.<span class="methodref">invokeFunction</span>("hello", "Scripting!!" );
    }
}

</code>
</pre>
<p>If your scripting language is object based (like JavaScript) or
object-oriented, then you can invoke a script method on a script
object.</p>
<pre><code>
// <a href="source/InvokeScriptMethod.java">InvokeScriptMethod.java</a>

import javax.script.*;

public class InvokeScriptMethod {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        // JavaScript code in a String. This code defines a script object 'obj'
        // with one method called 'hello'.        
        String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
        // evaluate script
        engine.eval(script);

        // <code>javax.script.Invocable</code> is an optional interface.
        // Check whether your script engine implements or not!
        // Note that the JavaScript engine implements Invocable interface.
        <span class="classref">Invocable</span> inv = (Invocable) engine;

        // get script object on which we want to call the method
        Object obj = engine.<span class="methodref">get</span>("obj");

        // invoke the method named "hello" on the script object "obj"
        inv.<span class="methodref">invokeMethod</span>(obj, "hello", "Script Method !!" );
    }
}

</code>
</pre>
<hr>
<a name="interfaces" id="interfaces"></a>
<h3>Implementing Java Interfaces by Scripts</h3>
<p>Instead of calling specific script functions from Java,
sometimes it is convenient to implement a Java interface by script
functions or methods. Also, by using interfaces we can avoid having
to use the <code>javax.script</code> API in many places. We can get
an interface implementor object and pass it to various Java APIs.
The following example demonstrates implementing the
<code>java.lang.Runnable</code> interface with a script.</p>
<pre><code>
// <a href="source/RunnableImpl.java">RunnableImpl.java</a>

import javax.script.*;

public class RunnableImpl {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        // JavaScript code in a String
        String script = "function run() { print('run called'); }";

        // evaluate script
        engine.eval(script);

        <span class="classref">Invocable</span> inv = (Invocable) engine;

        // get Runnable interface object from engine. This interface methods
        // are implemented by script functions with the matching name.
        Runnable r = inv.<span class="methodref">getInterface</span>(Runnable.class);

        // start a new thread that runs the script implemented
        // runnable interface
        Thread th = new Thread(r);
        th.start();
        th.join();
    }
}
</code>
</pre>
<p>If your scripting language is object-based or object-oriented,
it is possible to implement a Java interface by script methods on
script objects. This avoids having to call script global functions
for interface methods. The script object can store the "state"
associated with the interface implementor.</p>
<pre><code>
// <a href="source/RunnableImplObject.java">RunnableImplObject.java</a>

import javax.script.*;

public class RunnableImplObject {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        // JavaScript code in a String
        String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

        // evaluate script
        engine.eval(script);

        // get script object on which we want to implement the interface with
        Object obj = engine.<span class="methodref">get</span>("obj");

        <span class="classref">Invocable</span> inv = (Invocable) engine;

        // get Runnable interface object from engine. This interface methods
        // are implemented by script methods of object 'obj'
        Runnable r = inv.<span class="methodref">getInterface</span>(obj, Runnable.class);

        // start a new thread that runs the script implemented
        // runnable interface
        Thread th = new Thread(r);
        th.start();
        th.join();
    }
}
</code>
</pre>
<hr>
<a name="scopes" id="scopes"></a>
<h3>Multiple Scopes for Scripts</h3>
<p>In the <a href="#scriptvars">script variables</a> example, we
saw how to expose application objects as script global variables.
It is possible to expose multiple global "scopes" for scripts. A
single scope is an instance of <code>javax.script.Bindings</code>.
This interface is derived from <code>java.util.Map&lt;String,
Object&gt;</code>. A scope a set of name-value pairs where name is
any non-empty, non-null String.
<code>javax.script.ScriptContext</code> interface supports multiple
scopes with associated Bindings for each
scope. By default, every script engine has a default script
context. The default script context has atleast one scope called
"ENGINE_SCOPE". Various scopes supported by a script context are
available through <code>getScopes</code> method.</p>
<pre><code>
// <a href="source/MultiScopes.java">MultiScopes.java</a>

import javax.script.*;

public class MultiScopes {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        engine.put("x", "hello");
        // print global variable "x"
        engine.eval("print(x);");
        // the above line prints "hello"

        // Now, pass a different script context
        <span class="classref">ScriptContext</span> newContext = new <span class="classref">SimpleScriptContext</span>();
        newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
        <span class="classref">Bindings</span> engineScope = newContext.<span class="methodref">getBindings</span>(ScriptContext.ENGINE_SCOPE);

        // add new variable "x" to the new engineScope        
        engineScope.<span class="methodref">put</span>("x", "world");

        // execute the same script - but this time pass a different script context
        engine.eval("print(x);", newContext);
        // the above line prints "world"
    }
}

</code>
</pre>
<hr>
<a name="jsengine" id="jsengine"></a>
<h2>JavaScript Script Engine</h2>
<p>Oracle's implementation of JDK 8 is co-bundled with the Nashorn ECMAScript
script engine.
<hr>
<a name="jstojava" id="jstojava"></a>
<h2>JavaScript to Java Communication</h2>
<p>For the most part, accessing Java classes, objects and methods
is straightforward. In particular field and method access from
JavaScript is the same as it is from Java. We highlight important
aspects of JavaScript Java access here. 
The following examples are JavaScript snippets accessing Java. This
section requires knowledge of JavaScript. This section can be
skipped if you are planning to use some other JSR-223 scripting
language rather than JavaScript.</p>
<hr>
<a name="jsjavaclass" id=jsjavalass"></a>
<h3>Accessing Java Classes</h3>
<pre>
<code>
// <a href="source/javatypes.js">javatypes.js</a>

 var arrayListType = Java.type("java.util.ArrayList")
 var intType = Java.type("int")
 var stringArrayType = Java.type("java.lang.String[]")
 var int2DArrayType = Java.type("int[][]")
</code>
</pre> 

Note that the name of the type is always a string for a fully qualified name. You can use any of these types to create new instances, e.g.:

<pre><code>
 var anArrayList = new Java.type("java.util.ArrayList")
</code></pre> 

or

<pre><code>
 var ArrayList = Java.type("java.util.ArrayList")
 var anArrayList = new ArrayList
 var anArrayListWithSize = new ArrayList(16)
</code></pre> 

In the special case of inner classes, you need to use the JVM fully qualified name, meaning using $ sign in the class name:

<pre><code>
 var ftype = Java.type("java.awt.geom.Arc2D$Float")
</code></pre> 
 

However, once you retrieved the outer class, you can access the inner class as a property on it:

<pre><code>
 var arctype = Java.type("java.awt.geom.Arc2D")
 var ftype = arctype.Float
</code></pre> 
<p>
You 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.
</p>
<hr>
<a name="jsimport" id="jsimport"></a>
<h3>Importing Java Packages, Classes</h3>
<p>The built-in functions <code>importPackage</code> (in compatibility script) and
<code>importClass</code> can be used to import Java packages and
classes.</p>
<pre><code>

// <a href="source/importpackageclass.js">importpackageclass.js</a>

// load compatibility script
load("nashorn:mozilla_compat.js");
// Import Java packages and classes 
// like import package.*; in Java
<span class="functionref">importPackage</span>(java.awt);
// like import java.awt.Frame in Java
<span class="functionref">importClass</span>(java.awt.Frame);
// Create Java Objects by "new ClassName"
var frame = new java.awt.Frame("hello");
// Call Java public methods from script
frame.setVisible(true);
// Access "JavaBean" properties like "fields"
print(frame.title);
</code>
</pre>
<p>The <span class="objectref">Packages</span> global variable can
be used to access Java packages. Examples:
<code>Packages.java.util.Vector</code>,
<code>Packages.javax.swing.JFrame</code>. Please note that "java"
is a shortcut for "Packages.java". There are equivalent shortcuts
for javax, org, edu, com, net prefixes, so pratically all JDK
platform classes can be accessed without the "Packages" prefix.</p>
<p>Note that java.lang is not imported by default (unlike Java)
because that would result in conflicts with JavaScript's built-in
Object, Boolean, Math and so on.</p>
<p><code>importPackage</code> and <code>importClass</code>
functions "pollute" the global variable scope of JavaScript. To
avoid that, you may use <span class="functionref">JavaImporter</span>.</p>
<pre><code>

// <a href="source/javaimporter.js">javaimporter.js</a>

// create JavaImporter with specific packages and classes to import

var SwingGui = new <span class="functionref">JavaImporter</span>(javax.swing,
                            javax.swing.event,
                            javax.swing.border,
                            java.awt.event);
with (SwingGui) {
    // within this 'with' statement, we can access Swing and AWT
    // classes by unqualified (simple) names.

    var mybutton = new JButton("test");
    var myframe = new JFrame("test");
}

</code>
</pre>
<hr>
<a name="jsarrays" id="jsarrays"></a>
<h3>Creating, Converting and Using Java Arrays</h3>
<p>
Array element access or length access is
the same as in Java. Also, a script array can be used when a Java
method expects a Java array (auto conversion). So in most cases we
don't have to create Java arrays explicitly.</p>
<pre><code>
// <a href="source/javaarray.js">javaarray.js</a>

// create Java String array of 5 elements
var StringArray = Java.type("java.lang.String[]");
var a = new StringArray(5);

// Accessing elements and length access is by usual Java syntax
a[0] = "scripting is great!";
print(a.length);
print(a[0]);
</code>
</pre>
<p>
It is also possible to convert between JavaScript and Java arrays.
Given a JavaScript array and a Java type, <code>Java.toJavaArray</code> returns a Java array with the same initial contents, and with the specified component type. 
</p>
<pre><code>
 var anArray = [1, "13", false]
 var javaIntArray = Java.toJavaArray(anArray, "int")
 print(javaIntArray[0]) // prints 1
 print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
 print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
</code></pre>
<p>
Given a Java array or Collection, <code>Java.toJavaScriptArray</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.i
</p>
<pre><code>
var File = Java.type("java.io.File");
var listCurDir = new File(".").listFiles();
var jsList = Java.toJavaScriptArray(listCurDir);
print(jsList);
</code></pre>
<hr>
<a name="jsimplement" id="jsimplement"></a>
<h3>Implementing Java Interfaces</h3>
<p>A Java interface can be implemented in JavaScript by using a
Java anonymous class-like syntax:</p>
<pre><code>
// <a href="source/runnable.js">runnable.js</a>

var r  = new java.lang.Runnable() {
    run: function() {
        print("running...\n");
    }
};

// "r" can be passed to Java methods that expect java.lang.Runnable
var th = new java.lang.Thread(r);
th.start();
th.join();
</code>
</pre>
<p>When an interface with a single method is expected, you can pass
a script function directly.(auto conversion)</p>
<pre><code>
// <a href="source/samfunc.js">samfunc.js</a>

function func() {
     print("I am func!");
}

// pass script function for java.lang.Runnable argument
var th = new java.lang.Thread(func);
th.start();
th.join();
</code>
</pre>
<hr>
<a name="jsextend" id="jsextend"></a>
<h3>Extending Java classes</h3>
<p>
If 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.:
</p>

<pre><code>
 var TimerTask =  Java.type("java.util.TimerTask")
 var task = new TimerTask({ run: function() { print("Hello World!") } })
</code></pre>

Nashorn 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:

<pre><code>
 var task = new TimerTask {
     run: function() {
       print("Hello World!")
     }
 }
</code></pre>

which 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:

<pre><code>
 var task = new TimerTask(function() { print("Hello World!") })
</code></pre>

<p>
Note 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.
</p>
<p>
The 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:
</p>
<code><pre>
 Java.type("java.util.Timer")
 timer.schedule(function() { print("Hello World!") })
</code></pre>

Here, <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.

<p>
To extend a concrete Java class, you have to use <code>Java.extend</code> function.
<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.  
</p>
<pre><code>
// <a href="source/javaextend.js">javaextend.js</a>

var ArrayList = Java.type("java.util.ArrayList")
var ArrayListExtender = Java.extend(ArrayList)
var printSizeInvokedArrayList = new ArrayListExtender() {
    size: function() { print("size invoked!"); }
}
var printAddInvokedArrayList = new ArrayListExtender() {
    add: function(x, y) {
        if(typeof(y) === "undefined") {
            print("add(e) invoked!");
        } else {
            print("add(i, e) invoked!");
        }
    }
};
printSizeInvokedArrayList.size();
printAddInvokedArrayList.add(33, 33);
</code></pre>
<hr>
<a name="jsoverload" id="jsoverload"></a>
<h3>Overload Resolution</h3>
<p>Java methods can be overloaded by argument types. In Java,
overload resolution occurs at compile time (performed by javac).
When calling Java methods from a script, the script
interpreter/compiler needs to select the appropriate method. With
the JavaScript engine, you do not need to do anything special - the
correct Java method overload variant is selected based on the
argument types. But, sometimes you may want (or have) to explicitly
select a particular overload variant.</p>
<pre><code>
// <a href="source/overload.js">overload.js</a>

var out = java.lang.System.out;

// select a particular print function 
out["println(java.lang.Object)"]("hello");
</code>
</pre>
<hr>
<a name="engineimpl" id="engineimpl"></a>
<h2>Implementing Your Own Script Engine</h2>
<p>We will not cover implementation of JSR-223 compliant script
engines in detail. Minimally, you need to implement the
<code>javax.script.ScriptEngine</code> and
<code>javax.script.ScriptEngineFactory</code> interfaces. The
abstract class <code>javax.script.AbstractScriptEngine</code>
provides useful defaults for a few methods of the
<code>ScriptEngine</code> interface.</p>
<p>Before starting to implement a JSR-223 engine, you may want to
check <a href="http://java.net/projects/Scripting">http://java.net/projects/Scripting</a>
project. This project maintains JSR-223 implementations for many
popular open source scripting languages.</p>
<hr>
<a name="refs" id="refs"></a>
<h2>References</h2>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=223">JSR-223 Scripting
for the Java Platform</a></li>
<li><a href="http://java.net/projects/Scripting">http://java.net/projects/Scripting
</a></li>
</ul>



<div class="hr"><hr></div>
<table summary="layout" border="0" width="100%">
<tbody><tr valign="TOP">
<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>
<font size="+1"> <i>Java Technology</i></font> </td>

<td width="30%">
<p><font size="-2">
<a href="http://docs.oracle.com/javase/6/docs/legal/cpyr.html">Copyright </a> 2013, Oracle and/or its affiliates. All rights reserved.
</font></p> 
</td>
<td width="30%">
<p align="right"><font size="-2"><a href="http://download.oracle.com/javase/feedback.html">Contact Us</a></font></p><font size="-2">
</font></td>
</tr>
</tbody></table> 
<div class="hr"><hr></div>
</div>

<!-- Start SiteCatalyst code   -->
<script language="JavaScript" src="Java%20Scripting%20Programmer%27s%20Guide_files/s_code_download.js"></script>
<script language="JavaScript" src="Java%20Scripting%20Programmer%27s%20Guide_files/s_code.js"></script>
 
<!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** -->
<!--  Below code will send the info to Omniture server -->
<script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script>
 
<!-- End SiteCatalyst code -->



</body></html>