Anonymous classes are Groovy’s bag, once more

how-to
Oct 20, 20092 mins

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:

<pre class="prettyprint"><code>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.

<pre class="prettyprint"><code>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!

Looking to spin up Continuous Integration quickly? Check out www.ciinabox.com.
andrew_glover

When Andrew Glover isn't listening to “Funkytown” or “Le Freak” he enjoys speaking on the No Fluff Just Stuff Tour. He also writes articles for multiple online publications including IBM's developerWorks and O'Reilly’s ONJava and ONLamp portals. Andrew is also the co-author of Java Testing Patterns, which was published by Wiley in September 2004; Addison-Wesley’s Continuous Integration; and Manning’s Groovy in Action.

More from this author