Java Apache call StringUtils.join () from Groovy
I am trying to call Apache Commons StringUtils.join () method from Groovy class. I want to concatenate 3 lines ( part1
, part2
and part3
).
Why doesn't it work?
def path = StringUtils.join([part1, part2, part3]) //1
But the following line works:
def path = StringUtils.join([part1, part2, part3] as String[]) //2
Next question. Why does it work? I am using StringUtils v 2.6 so it doesn't have a varargs method. Groovy always converts method parameters to array?
def path = StringUtils.join(part1, part2, part3) //3
It's mostly a matter of curiosity. I am not going to use StringUtils because I posted a separate question yesterday and found a better solution. However, I would still like to understand why technique # 1 doesn't work, but # 3 works.
So, to show what's going on, write a script and show us what we get:
@Grab( 'commons-lang:commons-lang:2.6' )
import org.apache.commons.lang.StringUtils
def (part1,part2,part3) = [ 'one', 'two', 'three' ]
def path = StringUtils.join( [ part1, part2, part3 ] )
println "1) $path"
path = StringUtils.join( [ part1, part2, part3 ] as String[] )
println "2) $path"
path = StringUtils.join( part1, part2, part3 )
println "3) $path"
Prints:
1) [one, two, three]
2) onetwothree
3) onetwothree
Basically, only one of your method calls that matches the signature in the StringUtils class 2)
, as it matches the method definition Object[]
. For the other two, Groovy chooses the best match it can find for your method invocation.
For 1)
and 3)
he does the same. Wrapping parameters like Object[]
calling the same method as2)
For 3)
this is fine, since you get Object[]
with 3 elements, but for 1)
you get Object[]
with one element; yours List
.
The way to make it work with the List parameter would be using the spread operator like so:
path = StringUtils.join( *[ part1, part2, part3 ] )
println "4) $path"
What to print then:
4) onetwothree
As expected (it would put all the elements of the list as separate parameters and then put them in Object[]
with three elements like in the example3)