What does that mean?
It means that Nashorn provides complete interoperablity between JavaScript and Java worlds. i.e JavaScript code can directly call Java code, and vice versa. Nashorn also lets you create and manipulate Java objects, extend Java classes and implement Java interfaces. This interoperability also gives access to many additional tools and libraries and gives you the best of both worlds.Why Javascript?
Javascript as been really taking off along with the popularity of HTML5. Loads of libraries are being introduced every day and there are many Javascript developers out there as well. In fact, stats in 2013 show that there are almost as many Javascript developers as there are Java developers. Turns out Javascript it no longer 'just a' scripting language that is only used for front end development on browsers. :)How do you start using Nashorn?
You have two options- Command Line with jjs
Open up your cmd line and enter jjs
~>jjs
jjs> print("Hello World");
- Embed in Java code and use javax.script api
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
try {
e.eval("print('Hello World')");
} catch (ScriptException e1) {
e1.printStackTrace();
}
Examples
Calling Java methods
As you can see you may treat Java objects just like javascript objects. (Which is achived through InvokeDynamic - which I will come to later)Java arrays can be created as follows
Collections are interpreted as arrays
Here we are subclassing the abstract TimerTask class.
And since this is really javascript, we can directly pass in the function as a Lambda.
Similarly, functionality can be directly passed into a new thread (again as a Lambda)
Nashorn also integrates well with JavaFX. See this for a pretty cool demo. Just run it with jjs -fx -scripting fireworks.js
No comments:
Post a Comment