Java Reference
In-Depth Information
gramming to add a
toCamelCase
method to the
String
class to do the conversion. The
relevant code is
4
See
http://groovy.329449.n5.nabble.com/Change-uppercase-Sql-column-names-to-lowercase-td5712088.html
for
the complete discussion.
String.metaClass.toCamelCase = {->
delegate.toLowerCase().split('_')*.capitalize().join('').with {
take( 1 ).toLowerCase() + drop( 1 )
}
}
Every Groovy class has a metaclass retrieved by the
getMetaClass
method. New meth-
ods can be added to the metaclass by assigning closures to them, as is done here. A no-arg
closure is used, which implies that the new method will take zero arguments.
Inside the closure the
delegate
property refers to the object on which it was invoked.
In this case it's the string being converted. The database table columns are in uppercase
separated by underscores, so the delegate is converted to lowercase and then split at the
underscores, resulting in a list of strings.
Then the spread-dot operator is used on the list to invoke the
capitalize
method on
each one, which capitalizes only the first letter. The
join
method then reassembles the
string.
Then comes the fun part. The
with
method takes a closure, and inside that closure any
method without a reference is invoked on the delegate. The
take
and
drop
methods are
used on lists (or, in this case, a character sequence). The
take
method retrieves the num-
ber of elements specified by its argument. Here that value is 1, so it returns the first letter,
which is made lowercase. The
drop
method returns the rest of the elements after the num-
ber in the argument is removed, which in this case means the rest of the string.
The result is that you can call the method on a string and convert it.
'FIRST_NAME'
.toLowerCase()
becomes
'firstName'
, and so on.
Welcome to the wonderful world of Groovy metaprogramming.