Chapter 4. Using Groovy features in Java
This chapter covers
- Basic code-level simplifications
- Useful AST transformations
- XML processing
In chapter 1 I reviewed many of Java’s arguable weaknesses and drawbacks and suggested ways that Groovy might help ameliorate them. Because that chapter was intended to be introductory I only suggested how Groovy can help, without showing a lot of code examples. Now that I’ve established how easy it is to add Groovy classes to Java applications, when is it helpful to do so? What features, if any, does Groovy bring to Java systems that make them easier to develop?
A guide to the techniques covered in this chapter is shown in figure 4.1. I’ll review several Groovy advantages, like POGOs, operator overloading, the Groovy JDK, AST transformations, and how to use Groovy to work with XML and JSON data. To start, I’ll show that from Groovy code POJOs can be treated as though they were POGOs.
POGOs have more capabilities than POJOs. For example, all POGOs have a map-based constructor that’s very convenient for setting properties. The interesting thing is that even if a class is written in Java, many of the same conveniences apply as long as it’s accessed from Groovy.