<< December 13, 2006 | Home | December 15, 2006 >>

Groovy in GroovyEclipse

Groovy is not a scripting language!

There, I got that out of the way.

Often I see questions like Why use Groovy if it's like Java without types normally followed by responses showing examples of nice terse Groovy for various language constructs. I recently wrote some code for code completion of Default Groovy Methods which illustrates exactly why much of my plugin code is written in Groovy.

The completion idea is simple: Extract the methods from the DefaultGroovyMethods class, and create 2 lists of strings. One contains strings to display to the user in the completion popup, and the other contains strings that are inserted into the document after a completion is selected.

Often people look at Groovy snippets, and think all they are getting is Java with compact notation for lists, maps, strings and other types. The real fun is the compact way you can manipulate these commonly used types.

Back to the example. Place this Java code into your imagination:
Method[] methods = DefaultGroovyMethods.class.getMethods();
Now imagine all the iteration and string concatenation fun you will have.

Done?

Ok, now look at the Groovy code:
private static displayStrings = []
private static replaceStrings = []

static {
def methods = DefaultGroovyMethods.methods
methods = methods.findAll { java.lang.reflect.Modifier.isStatic(it.modifiers) }

// Get the display strings.
displayStrings = methods.collect { method ->
method.name + '(' +
method.parameterTypes.collect { it.simpleName } .join(',') +
") - ${method.returnType.simpleName}"
}

// Create replace strings - remember to convert from GStrings!
replaceStrings = methods.collect { "${it.name}()".toString() }
}
How easy was that?

It is important to note that this code is called from a Java class without any extra effort. A class file is a class file. And what magic do I need to do to export the plugin? Simply hit the magic 'export' button provided by Eclipse!