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 (
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.
source to share
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"
1) 2) onetwothree 3) onetwothree
Basically, only one of your method calls that matches the signature in the StringUtils class
, as it matches the method definition
. For the other two, Groovy chooses the best match it can find for your method invocation.
he does the same. Wrapping parameters like
calling the same method as
this is fine, since you get
with 3 elements, but for
with one element; yours
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:
As expected (it would put all the elements of the list as separate parameters and then put them in
with three elements like in the example
source to share