# Java Scripting Programmer's Guide

- Who is the Java Scripting API For?
- Scripting Package
- Examples
  - "Hello, World"
  - Evaluating a Script File
  - Script Variables
  - Invoking Script Functions and Methods
  - Implementing Java Interfaces by Scripts
  - Multiple Scopes for Scripts
- JavaScript Script Engine
- JavaScript to Java Communication
  - Accessing Java Classes
  - Importing Java Packages, Classes
  - Creating, Converting and Using Java Arrays
  - Implementing Java Interfaces
  - Extending Abstract Java Classes
  - Extending Concrete Java Classes
  - Implementing Multiple Java Interfaces
  - Class-Bound Implementations
  - Overload Resolution
  - Mapping of Data Types Between Java and JavaScript
- Implementing Your Own Script Engine
- References

## Who is the Java Scripting API For?

Some useful characteristics of scripting languages are:

- Convenience: 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.
- Developing rapid prototypes: You can avoid the edit-compile-run cycle and just use edit-run!
- Application extension/customization: You can "externalize" parts of your application - like configuration scripts, business logic/rules and math expressions for financial applications.
- "Command line" shells for applications -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.

The JavaTM 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.

## Scripting Package

The Java Scripting functionality is in the `javax.script` package. This is a relatively small, simple API. The starting point of the scripting API is the `ScriptEngineManager` 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:

1. Create a `ScriptEngineManager` object.
2. Get a `ScriptEngine` object from the manager.
3. Evaluate script using the `ScriptEngine`'s `eval` methods.

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.

## Examples

### "Hello, World"

From the `ScriptEngineManager` instance, we request a JavaScript engine instance using `getEngineByName` method. On the script engine, the `eval` 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 `javax.script` API. Needless to say, you have to handle the exceptions appropriately.

    // EvalScript.java

    import javax.script.*;
    public class EvalScript {
        public static void main(String[] args) throws Exception {
            // create a script engine manager
            ScriptEngineManager factory = new ScriptEngineManager();
            // create a JavaScript engine
            ScriptEngine engine = factory.getEngineByName("nashorn");
            // evaluate JavaScript code from String
            engine.eval("print('Hello, World')");
        }
    }

### Evaluating a Script File

In this example, we call the `eval` method that accepts `java.io.Reader` 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.

    // EvalFile.java

    import javax.script.*;

    public class EvalFile {
        public static void main(String[] args) throws Exception {
            // create a script engine manager
            ScriptEngineManager factory = new ScriptEngineManager();
            // create JavaScript engine
            ScriptEngine engine = factory.getEngineByName("nashorn");
            // evaluate JavaScript code from given file - specified by first argument
            engine.eval(new java.io.FileReader(args[0]));
        }
    }

Let us assume that we have the file named test.js with the following text:

    print("This is hello from test.js");

We can run the above Java as

    java EvalFile test.js

### Script Variables

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 `java.io.File` 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.

Nashorn script engine pre-defines two global variables named "context" and "engine". The "context" variable is of type javax.script.ScriptContext and refers to the current ScriptContext instance passed to script engine's eval method. The "engine" variable is of type javax.script.ScriptEngine and refers to the current nashorn script engine instance evaluating the script. Both of these variables are non-writable, non-enumerable and non-configurable - which implies script code can not write overwrite the value, for..loop iteration on global object will not iterate these variables and these variables can not be deleted by script.

    // ScriptVars.java

    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.put("file", f);

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

### Invoking Script Functions and Methods

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.

    // InvokeScriptFunction.java

    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);

            // javax.script.Invocable is an optional interface.
            // Check whether your script engine implements it or not!
            // Note that the JavaScript engine implements Invocable interface.
            Invocable inv = (Invocable) engine;

            // invoke the global function named "hello"
            inv.invokeFunction("hello", "Scripting!!" );
        }
    }

If your scripting language is object based (like JavaScript) or object-oriented, then you can invoke a script method on a script object.

    // InvokeScriptMethod.java

    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);

            // javax.script.Invocable is an optional interface.
            // Check whether your script engine implements or not!
            // Note that the JavaScript engine implements Invocable interface.
            Invocable inv = (Invocable) engine;

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

            // invoke the method named "hello" on the script object "obj"
            inv.invokeMethod(obj, "hello", "Script Method !!" );
        }
    }

### Implementing Java Interfaces by Scripts

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 `javax.script` API in many places. We can get an interface implementor object and pass it to various Java APIs. The following example demonstrates implementing the `java.lang.Runnable` interface with a script.

    // RunnableImpl.java

    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);

            Invocable inv = (Invocable) engine;

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

            // start a new thread that runs the script implemented
            // runnable interface
            Thread th = new Thread(r);
            th.start();
            th.join();
        }
    }

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.

    // RunnableImplObject.java

    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.get("obj");

            Invocable inv = (Invocable) engine;

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

            // start a new thread that runs the script implemented
            // runnable interface
            Thread th = new Thread(r);
            th.start();
            th.join();
        }
    }

### Multiple Scopes for Scripts

In the script variables 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 `javax.script.Bindings`. This interface is derived from `java.util.Map<String, Object>`. A scope a set of name-value pairs where name is any non-empty, non-null String. `javax.script.ScriptContext` 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 `getScopes` method.

    // MultiScopes.java

    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
            ScriptContext newContext = new SimpleScriptContext();
            newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
            Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

            // add new variable "x" to the new engineScope
            engineScope.put("x", "world");

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

## JavaScript Script Engine

Oracle's implementation of JDK 8 is co-bundled with the Nashorn ECMAScript script engine.

## JavaScript to Java Communication

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.

### Accessing Java Classes

    // javatypes.js

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

Note 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.:

     var anArrayList = new (Java.type("java.util.ArrayList"))

or

     var ArrayList = Java.type("java.util.ArrayList")
     var anArrayList = new ArrayList
     var anArrayListWithSize = new ArrayList(16)

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

     var ftype = Java.type("java.awt.geom.Arc2D$Float")

and

     var ftype = Java.type("java.awt.geom.Arc2D.Float")

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

     var arctype = Java.type("java.awt.geom.Arc2D")
     var ftype = arctype.Float

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.

In addition to creating new instances, the type objects returned from `Java.type` calls can also be used to access the static fields and methods of the classes:

     var File = Java.type("java.io.File")
     File.createTempFile("nashorn", ".tmp")

Methods with names of the form `isXxx()`, `getXxx()`, and `setXxx()` can also be used as properties, for both instances and statics.

A type object returned from `Java.type` is distinct from a `java.lang.Class` object. You can obtain one from the other using properties `class` and `static` on them.

     var ArrayList = Java.type("java.util.ArrayList")
     var a = new ArrayList

     // All of the following print true:
     print("Type acts as target of instanceof: " + (a instanceof ArrayList))
     print("Class doesn't act as target of instanceof: " + !(a instanceof a.getClass()))
     print("Type is not same as instance's getClass(): " + (a.getClass() !== ArrayList))
     print("Type's `class` property is same as instance getClass(): " + (a.getClass() === ArrayList.class))
     print("Type is same as instance getClass()'s `static` property: " + (a.getClass().static === ArrayList))

You can think of the type object as similar to the class names as used in Java source code: you use them as the arguments to the `new` and `instanceof` operators and as the namespace for the static fields and methods, but they are different than the runtime `Class` objects returned by `getClass()` calls. Syntactically and semantically, this separation produces code that is most similar to Java code, where a distinction between compile-time class expressions and runtime class objects also exists. (Also, Java can't have the equivalent of `static` property on a `Class` object since compile-time class expressions are never reified as objects).

### Importing Java Packages, Classes

The built-in functions `importPackage` (in compatibility script) and `importClass` can be used to import Java packages and classes.

    // importpackageclass.js

    // load compatibility script
    load("nashorn:mozilla_compat.js");
    // Import Java packages and classes
    // like import package.*; in Java
    importPackage(java.awt);
    // like import java.awt.Frame in Java
    importClass(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);

The Packages global variable can be used to access Java packages. Examples: `Packages.java.util.Vector`, `Packages.javax.swing.JFrame`. 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.

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.

`importPackage` and `importClass` functions "pollute" the global variable scope of JavaScript. To avoid that, you may use JavaImporter.

    // javaimporter.js

    // create JavaImporter with specific packages and classes to import

    var SwingGui = new JavaImporter(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");
    }

### Creating, Converting and Using Java Arrays

Array element access or length access is the same as in Java.

    // javaarray.js

    // 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]);

It is also possible to convert between JavaScript and Java arrays. Given a JavaScript array and a Java type, `Java.to` returns a Java array with the same initial contents, and with the specified array type.

     var anArray = [1, "13", false]
     var javaIntArray = Java.to(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

You can use either a string or a type object returned from `Java.type()` to specify the type of the array. You can also omit the array type, in which case a `Object[]` will be created.

Given a Java array or Collection, `Java.from` 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.

    var File = Java.type("java.io.File");
    var listCurDir = new File(".").listFiles();
    var jsList = Java.from(listCurDir);
    print(jsList);

### Implementing Java interfaces

A Java interface can be implemented in JavaScript by using a Java anonymous class-like syntax:

    // runnable.js

    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();

When an interface with a single method is expected, you can pass a script function directly.(auto conversion)

    // samfunc.js

    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();

### Extending Abstract Java Classes

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

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

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:

     var task = new TimerTask {
         run: function() {
           print("Hello World!")
         }
     }

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:

     var task = new TimerTask(function() { print("Hello World!") })

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.

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:

`

     Java.type("java.util.Timer")
     timer.schedule(function() { print("Hello World!") })

` Here, `Timer.schedule()` expects a `TimerTask` 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.

### Extending Concrete Java Classes

To extend a concrete Java class, you have to use `Java.extend` function. `Java.extend` 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.

    // javaextend.js

    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);

The reason you must use `Java.extend()` with concrete classes is that with concrete classes, there can be a syntactic ambiguity if you just invoke their constructor. Consider this example:

    var t = new java.lang.Thread({ run: function() { print("Hello!") } })

If we allowed subclassing of concrete classes with constructor syntax, Nashorn couldn't tell if you're creating a new `Thread` and passing it a `Runnable` at this point, or you are subclassing `Thread` and passing it a new implementation for its own `run()` method.

### Implementing Multiple Interfaces

`Java.extend` can in fact take a list of multiple types. At most one of the types can be a class, and the rest must be interfaces (the class doesn't have to be the first in the list). You will get back an object that extends the class and implements all the interfaces. (Obviously, if you only specify interfaces and no class, the object will extend `java.lang.Object`).

### Class-Bound Implementations

The methods shown so far for extending Java classes and implementing interfaces – passing an implementation JavaScript object or function to a constructor, or using `Java.extend` with `new` – all produce classes that take an extra JavaScript object parameter in their constructors that specifies the implementation. The implementation is therefore always bound to the actual instance being created with `new`, and not to the whole class. This has some advantages, for example in the memory footprint of the runtime, as Nashorn can just create a single "universal adapter" for every combination of types being implemented. In reality, the below code shows that different instantiations of, say, `Runnable` have the same class regardless of them having different JavaScript implementation objects:

    var Runnable = java.lang.Runnable;
    var r1 = new Runnable(function() { print("I'm runnable 1!") })
    var r2 = new Runnable(function() { print("I'm runnable 2!") })
    r1.run()
    r2.run()
    print("We share the same class: " + (r1.class === r2.class))

prints:

    I'm runnable 1!
    I'm runnable 2!
    We share the same class: true

Sometimes, however, you'll want to extend a Java class or implement an interface with implementation bound to the class, not to its instances. Such a need arises, for example, when you need to pass the class for instantiation to an external API; prime example of this is the JavaFX framework where you need to pass an Application class to the FX API and let it instantiate it.

Fortunately, there's a solution for that: `Java.extend()` – aside from being able to take any number of type parameters denoting a class to extend and interfaces to implement – can also take one last argument that has to be a JavaScript object that serves as the implementation for the methods. In this case, `Java.extend()` will create a class that has the same constructors as the original class had, as they don't need to take an an extra implementation object parameter. The example below shows how you can create class-bound implementations, and shows that in this case, the implementation classes for different invocations are indeed different:

    var RunnableImpl1 = Java.extend(java.lang.Runnable, function() { print("I'm runnable 1!") })
    var RunnableImpl2 = Java.extend(java.lang.Runnable, function() { print("I'm runnable 2!") })
    var r1 = new RunnableImpl1()
    var r2 = new RunnableImpl2()
    r1.run()
    r2.run()
    print("We share the same class: " + (r1.class === r2.class))

prints:

    I'm runnable 1!
    I'm runnable 2!
    We share the same class: false

As you can see, the major difference here is that we moved the implementation object into the invocation of `Java.extend` from the constructor invocations – indeed the constructor invocations now don't even need to take an extra parameter! Since the implementations are bound to a class, the two classes obviously can't be the same, and we indeed see that the two runnables no longer share the same class – every invocation of `Java.extend()` with a class-specific implementation object triggers the creation of a new Java adapter class.

Finally, the adapter classes with class-bound implementations can still take an additional constructor parameter to further override the behavior on a per-instance basis. Thus, you can even combine the two approaches: you can provide part of the implementation in a class-based JavaScript implementation object passed to `Java.extend`, and part in another object passed to the constructor. Whatever functions are provided by the constructor-passed object will override the functions in the class-bound object.

    var RunnableImpl = Java.extend(java.lang.Runnable, function() { print("I'm runnable 1!") })
    var r1 = new RunnableImpl()
    var r2 = new RunnableImpl(function() { print("I'm runnable 2!") })
    r1.run()
    r2.run()
    print("We share the same class: " + (r1.class === r2.class))

prints:

    I'm runnable 1!
    I'm runnable 2!
    We share the same class: true

### Overload Resolution

Java methods can be overloaded by argument types. In Java, overload resolution occurs at compile time (performed by javac). When calling Java methods from Nashorn, the appropriate method will be selected based on the argument types at invocation time. You do not need to do anything special – the correct Java method overload variant is selected based automatically. You still have the option of explicitly specifying a particular overload variant. Reasons for this include either running into a genuine ambiguity with actual argument types, or rarely reasons of performance – if you specify the actual overload then the engine doesn't have to perform resolution during invocation. Individual overloads of a Java methods are exposed as special properties with the name of the method followed with its signature in parentheses. You can invoke them like this:

    // overload.js

    var out = java.lang.System.out;

    // select a particular print function
    out["println(Object)"]("hello");

Note that you normally don't even have to use qualified class names in the signatures as long as the unqualified name of the type is sufficient for uniquely identifying the signature. In practice this means that only in the extremely unlikely case that two overloads only differ in parameter types that have identical unqualified names but come from different packages would you need to use the fully qualified name of the class.

### Mapping of Data Types Between Java and JavaScript

We have previously shown some of the data type mappings between Java and JavaScript. We saw that arrays need to be explicitly converted. We have also shown that JavaScript functions are automatically converted to SAM types when passed as parameters to Java methods. Most other conversions work as you would expect.

Every JavaScript object is also a `java.util.Map` so APIs receiving maps will receive them directly.

When numbers are passed to a Java API, they will be converted to the expected target numeric type, either boxed or primitive, but if the target type is less specific, say `Number` or `Object`, you can only count on them being a `Number`, and have to test specifically for whether it's a boxed `Double`, `Integer`, `Long`, etc. – it can be any of these due to internal optimizations. Also, you can pass any JavaScript value to a Java API expecting either a boxed or primitive number; the JavaScript specification's `ToNumber` conversion algorithm will be applied to the value.

In a similar vein, if a Java method expects a `String` or a `Boolean`, the values will be converted using all conversions allowed by the JavaScript specification's `ToString` and `ToBoolean` conversions.

Finally, a word of caution about strings. Due to internal performance optimizations of string operations, JavaScript strings are not always necessarily of type `java.lang.String`, but they will always be of type `java.lang.CharSequence`. If you pass them to a Java method that expects a `java.lang.String` parameter, then you will naturally receive a Java String, but if the signature of your method is more generic, i.e. it receives a `java.lang.Object` parameter, you can end up with an object of private engine implementation class that implements `CharSequence` but is not a Java String.

## Implementing Your Own Script Engine

We will not cover implementation of JSR-223 compliant script engines in detail. Minimally, you need to implement the `javax.script.ScriptEngine` and `javax.script.ScriptEngineFactory` interfaces. The abstract class `javax.script.AbstractScriptEngine` provides useful defaults for a few methods of the `ScriptEngine` interface.

Before starting to implement a JSR-223 engine, you may want to check http://java.net/projects/Scripting project. This project maintains JSR-223 implementations for many popular open source scripting languages.

## References

- JSR-223 Scripting for the Java Platform
- http://java.net/projects/Scripting

Java Technology | Copyright © 2013, Oracle and/or its affiliates. All rights reserved. | Contact Us