Reputation: 150
I am using mvn archetype:generate to templatize some stuff in my project. I'm running into some trouble with the Maven 3.2.2 Velocity Engine split() method. I havent been able to figure out specifically what version of Velocity Maven is using.
#set($foo = "one:a, two:b, three:c")
$!foo
$foo.split(",")
#foreach($bar in $foo.split(","))
$!bar
$bar.split(":")
#set($number = $bar.split(":").get(0))
number = $!number
#set($letter = $bar.split(":").get(1))
letter = $!letter
#end
Expected output:
one:a, two:b, three:c
['one:a', 'two:b', 'three:c']
one:a
['one', 'a']
number = one
letter = a
two:b
...
Actual output:
one:a, two:b, three:c
[Ljava.lang.String;@6cff380
one:a
[Ljava.lang.String;@5a587f23
number =
letter =
two:b
[Ljava.lang.String;@2c8b586a
...
As you can see, the first split() used in the #foreach block works as I expect splitting the string by commas and iterating over the three substrings, but when I print $bar.split(":") I get that weird String pointer and #set($number = $bar.split(":").get(0)) prints nothing because .get() is being called on a String instead of an Array. With that in mind I was able to come up with this horrible hack:
#foreach ($bar in $foo.split(","))
#set ($i = 0)
#foreach($hack in $bar.split(":"))
#if($i == 0)
#set ($number = $hack)
#else
#set ($letter = $hack)
#end
#set($i = $i + 1)
#end
number = $number
letter = $letter
#end
But there has to be a better way, I cannot use this code in good conscience. I've been using Velocity for a grand total of 3 hours so I am surely to blame here, what does #foreach know that I don't?
Thanks for the help.
Edit: according to this maven archetype is using Velocity Engine 1.5
Upvotes: 1
Views: 2430
Reputation: 460
Claude's answer was helpful, but what if you can't use a newer version of Velocity? I'm stuck with a version of Liferay that uses Velocity 1.5!
Velocity 1.3 and higher come with ListTool, which can get the list members for you:
#set($number = $listTool.get($bar.split(":"),0)
#set($letter = $listTool.get($bar.split(":"),1)
That should give you your expected output. It worked for me!
Upvotes: 0
Reputation: 4130
[Ljava.lang.String;@6cff380
is not a string reference, it's a string array reference, so up to this point, eveything is normal (except maybe that Velocity could format the array instead of outputting its toString() method).
Then, when you call get(i)
on an array, you don't get anything, whereas since Velocity 1.6 you should get what you want, that is the ith element. I just guess your version of Velocity is too old...
Upvotes: 2