Wednesday

Java Fun Continued - Groovy FTW

Here's the equivalent Groovy for my previous Java abomination that prints the Java wrapper methods for me:

new File("src/main/java/Foo.java").text.
replaceAll(/(?sm)\s*public\s+(\S+)\s+(\S+)\((.*?)\)\s*\{/) {
s,ret,name,params ->
print """
public ${ret} ${name}(${params}) {
"""
if("void" != ret) {
print "return "
}
print "foo.${name}("
// -1 hack avoids index out of bounds when params is ''
print params.trim().split(/\s*,\s*/).collect {
it.split(/\s+/)[-1]
}.join(',')
print """);
}
"""
}

I could change the prints to concatenation and reformat the whole thing as a single line, so it only counts as one statement. Technically I cheated a little because this version doesn't look up the methods by reflection, but it doesn't make a difference in the result, and wouldn't significantly shorten the Java code. Definitely more readable than the Java. The JavaScript is a little messier since you don't have multi-line string literals, GStrings, and closures are function(it){ return it.foo; } instead of { it.foo }.

No comments: