Search

Dark theme | Light theme

August 14, 2009

Groovy Goodness: Use a Map as Interface Implementation

To implement an interface we can use a Groovy map and with the as keyword we can pass it on to a method. Here is a simple example where we define an implementation of the java.io.FileFilter as a map. We pass the implementation on to the java.io.File.listFiles() method to display all files with extensions .css and .png:

map = [ 
    // Implement FileFilter.accept(File) method.
    accept: { file -> file.path ==~ /.*\.(css|png)$/ } 
] as FileFilter
new File('c:/temp').listFiles(map).each { 
    println it.path 
}

If the interface we want to implement has more than one method we can only use a map for the implementation. But if the interface only contains one method (as in this case) we can also use a closure for the implementation. In the following example we implement the java.io.FileFilter interface with a closure to filter all files with the extension .jpg:

filter = { it.path ==~ /.*\.jpg$/ }
new File('c:/temp').listFiles(filter as FileFilter).each { file ->
    println file.path
}