Anonymous classes are Groovy’s bag, once more

Posted by: Andrew Glover on 2009-10-20 15:17:00.0

As I elaborated previously, Groovy

does not formally support the creation of anonymous inner classes.

Yet, as I demonstrated, you can coerce a hip Map into an interface type rather easily. Map coercion, however, isn’t the only way to mimic an anonymous class in Groovy. You can also coerce a closure into an interface type. This is easiest when the method you wish to implement only has one method.

For example, imagine a simple interface, defined in Java no less, called Filterable:

public interface Filterable {
 boolean filter(String value);
}

One way to anonymously implement this type is by defining a closure that implements your desired behavior. Inside the closure, you code the intended behavior of the interface method (like filter, in my case) and then, after the body of the closure, you cast the closure to the interface type.

For example, as the easyb story demonstrates below, I can implement the Filterable interface, leverage it later and even prove that the resulting variable is of type Filterable.

scenario "a closure in Groovy can act as an anonymous class using the 'as' keyword",{

 given "a closure cast via 'as' to an interface with a single method",{
  palindrome = {
    return (it.reverse() == it)
  } as Filterable
 }

 then "the resulting object behaves like the implemented interface", {
  palindrome.filter("kayak").shouldBe true
  palindrome.filter("Andrew").shouldBe false
 }

 and "the object's type is the implemented interface", {
  (palindrome instanceof Filterable).shouldBe true
 }
}

In the case of casting closures, as opposed to Map coercion, it becomes less readable if the implementing interface has more than one method as Groovy, under the covers, invokes the closure for each method on the interface. In that case, Map coercion is much more read-able, baby!

You can now follow The Disco Blog on Twitter, baby!


be the first to rate this blog


About Andrew Glover

Andrew is the founder of the easyb BDD framework and the co-author of Addison Wesley's "Continuous Integration", Manning's "Groovy in Action" and "Java Testing Patterns". He is an author for multiple online publications including IBM's developerWorks and Oreilly's ONJava and ONLamp portals. He actively blogs about software at thediscoblog.com.