E-Book, Englisch, 394 Seiten
Adamovich / Fiandesio Groovy 2 Cookbook
1. Auflage 2025
ISBN: 978-1-84951-937-3
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)
Java and Groovy go together like ham and eggs, and this book is a great opportunity to learn how to exploit Groovy 2 to the full. Packed with recipes, both intermediate and advanced, it's a great way to speed up and modernize your programming.
E-Book, Englisch, 394 Seiten
ISBN: 978-1-84951-937-3
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)
Get up to speed with Groovy, a language for the Java Virtual Machine (JVM) that integrates features of both object-oriented and functional programming. This book will show you the powerful features of Groovy 2 applied to real-world scenarios and how the dynamic nature of the language makes it very simple to tackle problems that would otherwise require hours or days of research and implementation.
Groovy 2 Cookbook contains a vast number of recipes covering many facets of today's programming landscape. From language-specific topics such as closures and metaprogramming, to more advanced applications of Groovy flexibility such as DSL and testing techniques, this book gives you quick solutions to everyday problems.
The recipes in this book start from the basics of installing Groovy and running your first scripts and continue with progressively more advanced examples that will help you to take advantage of the language's amazing features.
Packed with hundreds of tried-and-true Groovy recipes, Groovy 2 Cookbook includes code segments covering many specialized APIs to work with files and collections, manipulate XML, work with REST services and JSON, create asynchronous tasks, and more. But Groovy does more than just ease traditional Java development: it brings modern programming features to the Java platform like closures, duck-typing, and metaprogramming.
In this new book, you'll find code examples that you can use in your projects right away along with a discussion about how and why the solution works. Focusing on what's useful and tricky, Groovy 2 Cookbook offers a wealth of useful code for all Java and Groovy programmers, not just advanced practitioners.
Autoren/Hrsg.
Fachgebiete
Weitere Infos & Material
Embedding Groovy into Java
There are plenty of scripting languages available at the moment on the JVM. Some of them only offer expression language support for data binding and configuration needs, for example, MVEL (http://mvel.codehaus.org/) and SpEL (Spring Expression Language, http://www.springsource.org/documentation). Others provide a fully featured programming language. Examples of these are JRuby, Jython, Clojure, Jaskell, and of course, Groovy.
In this recipe, we will show you how to benefit from Groovy scripting from within your Java application.
Getting ready
To embed Groovy scripts into your Java code base, first of all, you need to add library to your class path. Or if you are using Java 7 and want to take advantage of the optimization, you should add instead (see also the recipe in Chapter 1, ).
These libraries are located inside the Groovy distribution archive under the folder. Another way to get those JAR files is from Maven Central Repository at http://search.maven.org/.
The artifact contains all the required classes to run Groovy code. It also includes dependencies such as Antlr, ASM, and Apache Commons inside the archive to be able to run Groovy with only single JAR on the class path. However, you shouldn't worry about class version conflicts if you use one of these libraries because all foreign classes are placed under special packages inside the library.
How to do it...
There are several ways in which a Groovy script can be invoked from your Java application, but the recommended one—and also the simplest—is using the class.
- Let's start by creating a new Java class named that has the following content: import groovy.lang.GroovyShell; import groovy.lang.Script; import java.io.File; import java.io.IOException; import org.codehaus.groovy.control.CompilationFailedException; public class CallGroovyUsingGroovyShell { public static void main(String[] args) throws CompilationFailedException,IOException { // Create shell object. GroovyShell shell = new GroovyShell(); double result = (Double) shell. evaluate("(4/3) * Math.PI * 6370 " + "// Earth volume in cubic killometeres "); System.out.println(result); } }
The class instantiates a object and calls the method of the object by passing a containing Groovy code.
- Let's explore more methods of the class by adding the following Java code to the method: shell.evaluate("name = 'Andrew'"); shell.setVariable("name", "Andrew"); shell.evaluate("println \"My name is ${name}\""); shell.evaluate("name = name.toUpperCase()"); System.out.println(shell.getVariable("name")); System.out.println(shell.getProperty("name")); shell.evaluate("println 'Hello from shell!'"); System.out.println(shell.evaluate(" 1 + 2 "));
- In the same folder where the newly created Java class is located, place a Groovy script named , with the following content: def scriptName = 'external script' name = scriptName println "Hello from ${name} on ${currentDate}!" def getCurrentDate() { new Date().format('yyyy-MM-dd') }
- Let's continue by adding a new line to the method of our Java class: shell.evaluate(new File("script.groovy"));
- Now compile and run the class. The library must be located in the same folder as the Java and the Groovy file.
On Linux/OS X:
javac -cp groovy-all-2.1.6.jar CallGroovyUsingGroovyShell.java java -cp .:groovy-all-2.1.6.jar CallGroovyUsingGroovyShellOn Windows:
javac -cp groovy-all-2.1.6.jar CallGroovyUsingGroovyShell.java java -cp .;groovy-all-2.1.6.jar CallGroovyUsingGroovyShellThe output should look as follows:
6682.593603822243 My name is Andrew My name is Andrew ANDREW ANDREW Hello from shell! 3 Hello from external script on 2013-08-31! - Let's add more examples to the class. Append the following lines to the method of the class: Script script = shell.parse(new File("script.groovy")); script.run(); System.out.println(script. invokeMethod("getCurrentDate", null)); System.out.println(script.getProperty("name")); // Calling internal script script = shell.parse("println 'Hello from internal script!'"); script.run(); script = shell.parse(new File("functions.groovy")); System.out.println(script.invokeMethod("year", null));
- Add one more Groovy file to the list of files for this recipe, named : def year() { Calendar.instance.get(Calendar.YEAR) } def month() { Calendar.instance.get(Calendar.MONTH) } def day() { Calendar.instance.get(Calendar.DAY_OF_MONTH) }
- Compile and run again; the additional output should look as follows: Hello from external script on 2013-08-31! 2013-08-31 external script Hello from internal script! 2013
How it works...
In the Java class example, the object is instantiated using the default constructor.
In step 1, the Groovy code passed to the method calculates the result of the simple arithmetical expression. No statement is used, but still the expression evaluates correctly. The reason is that in Groovy, the statement is optional, and an expression will always return the value of the last statement. The mathematical expression's result type is as we only operate with floating numbers; this is why we can safely cast it.
Furthermore, the expression refers to a constant defined in the class, without explicitly importing it. This is possible due to the fact that Groovy imports all classes automatically, just like Java.
There is also a comment at the end of the expression, which is safely ignored. Similar to Java, comments can appear anywhere in Groovy code.
The object supports defining global variables, which can be re-used by evaluated scripts, by using the method, as displayed in step 2.
The variable is set and then used inside a script evaluated later. The variable will be available to all the scripts executed throughout the lifetime of the object.
The variable's value can also be changed during script execution and retrieved later using the method.
In step 3, we can observe another useful feature of the integration of Groovy with Java; the possibility of executing external Groovy scripts from Java by passing a object to the method.
You can also create individual objects for repeated executions:
In this case, the script code will be compiled by the method and the script execution will be faster than if we do repeated calls of the method.
Steps 6 and 7 show how you can also execute individual methods if they are defined by the code located in an external script. Once the script is successfully compiled, the can be used to call any function declared in the external script.
There's more...
If you are familiar with JSR-223, which provides the specification for the Java SE scripting API, you can also use it with Groovy. JSR-223 is recommended over the approach if you want to be able to switch to a different scripting language at any point. The next example shows how to get started with the scripting API:
The key to start using Groovy with JSR-233 is again to add the artifact to the classpath. Adding the jar will automatically bind the Groovy script engine into JVM, which can be retrieved by a call to as shown in the previous example. Please note that the JSR-233 specification is only available from Java 6.
Another way to dynamically embed Groovy into Java code is by defining the Groovy classes and parsing them with...




