Reputation: 393
I just start using Java Velocity. Now I want to create a java class template.
package $app.package_namespace
public class ${app.name}Station
{
#foreach($s_attribute in $app.station)
$s_attribute.type $s_attribute.name,
#end
public $app.name Station(#foreach($s_attribute in $app.station)
$s_attribute.type $s_attribute.name;
#end)
{
#foreach($s_attribute in $app.station)
$s_attribute.name=$s_attribute.name;
#end
}
#foreach($s_attribute in $app.station)
public ${s_attribute.type} get${s_attribute.name}()
{
return get${s_attribute.name}();
}
#end
}
The problem is s_attribute.name first character is lowercase. When I create getter and setter function for attributes. I need change first character to uppercase.
Did anyone know how to do it?
Upvotes: 35
Views: 62938
Reputation: 111265
There is capitalize()
method in DisplayTool
. In the template you can do:
get${display.capitalize($s_attribute.name)}()
You will need the extra dependency on the classpath:
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>3.1</version>
</dependency>
And you need to add a the display
instance to the context
VelocityContext context = new VelocityContext();
context.put("display", new DisplayTool());
Upvotes: 14
Reputation: 3602
If you are using commons-lang
you can use the StringUtils
class:
context.put("StringUtils", org.apache.commons.lang3.StringUtils.class);
Then in your template:
...
return get$StringUtils.capitalize(s_attribute.name)();
...
Upvotes: 4
Reputation: 12664
You could just create 2 methods getName()
and getname()
then when you use ${s_attribute.name}
velocity will use getname()
and when you use ${s_attribute.Name}
velocity will use the getName()
method.
From the Velocity guide:
Property Lookup Rules
As was mentioned earlier, properties often refer to methods of the parent object. Velocity is quite clever when figuring out which method corresponds to a requested property. It tries out different alternatives based on several established naming conventions. The exact lookup sequence depends on whether or not the property name starts with an upper-case letter. For lower-case names, such as $customer.address, the sequence is
getaddress() getAddress() get("address") isAddress()
For upper-case property names like $customer.Address, it is slightly different:
getAddress() getaddress() get("Address") isAddress()
What i'm suggesting is that you handle it in your object on the backend.
Upvotes: 2
Reputation: 8036
You can invoke standard java methods on these objects. If s_attribute.name
is type String you can directly use $s_attribute.name.toUpperCase()
or for your specific case use $s_attribute.name.substring(0,1).toUpperCase()
and $s_attribute.name.substring(1).toLowerCase()
Upvotes: 44