Java Reference
In-Depth Information
given:
Employee fred = new Employee(name:'Fred',id:1)
when:
dept = dept << fred
then:
dept.employees.size() == old(dept.employees.size()) + 1
}
def "add two employees via chained left shift"() {
given:
Employee fred = new Employee(name:'Fred',id:1)
Employee barney = new Employee(name:'Barney',id:2)
when:
dept = dept << fred << barney
then:
dept.employees.size() == 2
}
}
The Spock test is written in Groovy, so I can use +, -, and << and know that the associated
methods will be used, even though they're implemented in a Java class.
The list of operators that can be overridden in Groovy includes plus , minus , and
leftShift , as shown in the listing, and many others as well. You can implement array-
like access through an index by implementing getAt , for example. Pre-and post-incre-
ment are implemented through the next and previous methods, respectively. The
spaceship operator, <=>, is implemented through compareTo . You can even override the
dot operator, believe it or not. The cool part is that you can implement these methods in
either POJOs or POGOs, and Groovy will take advantage of them either way.
The next feature ofGroovythat simplifies Java is one I've taken advantage ofseveral times
already: the Groovy JDK.
4.3. Making Java library classes better: the Groovy JDK
Every Groovy class contains a metaclass. In addition to providing information about a
class, the metaclass contains methods that come into play if a method or property that
Search WWH ::




Custom Search