public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval("print('Hello JavaScript in Java')");
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
In Listing 22-2, an instance of ScriptEngine interface is retrieved from the ScriptEngineManager
class, using the name JavaScript. Then, the ScriptEngine.eval() method is called, passing in a String
argument, which contains a JavaScript expression. Note that the argument can also be a java.io.Reader
class, which can read JavaScript from a file. Running the program will produce the following result:
Hello JavaScript in Java
This should give you an idea of how to run scripts in Java. However, it's not of much interest to just
dump some output using another language. In the next section, we will introduce Groovy, a powerful
and comprehensive scripting language.
Introducing Groovy
Started by James Strachan in 2003, the main objective of Groovy is to provide an agile and dynamic
language for the JVM, with features inspired from other popular scripting languages including Python,
Ruby, and Smalltalk. Groovy is built on top of Java, extends Java, and addresses some of the
shortcomings in Java.
In the following sections, we will discuss some main features and concepts behind Groovy and how
it supplements Java to address specific application needs. Note that many features mentioned here also
are available in other scripting languages (for example, Scala, Erlang, Python, and Clojure).
Dynamic Typing
One main difference between Groovy (and many other scripting languages) and Java is the support of
dynamic typing of variables. In Java, all properties and variables should be statically typed. In other
words, the type should be provided with the declare statement. However, Groovy supports the dynamic
typing of variables. In Groovy, dynamic typing variables are declared with the keyword def.
Let's see this in action by developing a simple Groovy script. The file suffix of a Groovy class or script
is groovy. In STS, in a project with Groovy enabled, you can create a Groovy class or script by right-
clicking the package name, choosing New Other, and then selecting the Groovy class.
Listing 22-3 shows a simple Groovy script with dynamic typing in action (the file name is
DynamicTyping.groovy).
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home