Java Reference
In-Depth Information
javaDev.first = "Joe";
javaDev.last = "Dynamic";
print(javaDev + "'s gross pay for the week is: "
+ javaDev.grossPay(new bigDecimal(60),
bigDecimal(80)));
Here's the result:
Joe Dynamic's gross pay for the week is: 5300
How It Works
To extend a standard Java class from within JavaScript, you call on the
Java.extend() function, passing the Java class that you'd like to extend, along
with a JavaScript object containing any fields or functions that will be altered in the
subclass. For the example in this recipe, a Java class entitled Employee is extended.
However, the same technique can be used to extend any other Java interface, such as
Runnable, Iterator, and so on.
In this example, to obtain the Employee class in JavaScript, the Java.type()
function is called upon, passing the fully qualified class name. The object that is re-
ceived from the call is stored in a JavaScript variable named Employee . Next, the
class is extended by calling on the Java.extend() function and passing the Em-
ployee class, along with a JavaScript object. In the example, the JavaScript object
that is sent to the Java.extend() function includes a different implementation of
the Employee class grossPay() method. The object that is returned from the
Java.extend() function is then instantiated and accessed via JavaScript.
Extending Java classes within JavaScript can be a very useful feature when you're
working with a Nashorn solution. The ability to share objects from Java makes it pos-
sible to access exiting Java solutions and build on them.
18-10.
Creating
Executable
Scripts
in
Unix
Problem
Search WWH ::




Custom Search