Here is my object class:
public class Address
{
public final String line1;
public final String town;
public final String postcode;
public Address(final String line1, final String town, final String postcode)
{
this.line1 = line1;
this.town = town;
this.postcode = postcode;
}
}
I add it to the velocity context like this:
Address theAddress = new Address("123 Fake St", "Springfield", "SP123");
context.put("TheAddress", theAddress);
However, when writing the template, the following will not render the address fields (however, it works fine when I add getters to the Address class)
<Address>
<Line1>${TheAddress.line1}</Line1>
<Town>${TheAddress.town}</Town>
<Postcode>${TheAddress.postcode}</Postcode>
</Address>
Is it possible to access public fields on objects from Velocity without adding getters?
The Velocity user guide suggests it's not possible. Quote:
i do
And all works OK!!!
Not by default. You need to configure a different Uberspect implementation.
http://wiki.apache.org/velocity/VelocityFAQ:
FieldMethodizer
works only with public static fields.PublicFieldUberspect
example code is quite old and it just fails with error on nonexistent fields.And forget about lobby at dev list. )
Meanwhile, there is good caching implementation of UberspectPublicFields in current velocity trunk. Unfortunately, there was no active development for years and no plans for next release are published. One would have to build it himself and bundle in private repository.
Another altervative is a fork with bonus scala compatibility that is available in central maven repository: http://maven-repository.com/artifact/com.sksamuel.scalocity/scalocity/0.9.
Drop in instead of usual velocity dependency:
Then just add to
velocity.properties
:The caveat is that
UberspectImpl
is patched with additional support for scala properties and requires 8 MB scala jar.Eventually, I just interned the following classes from velocity trunk into own project:
These work fine with Velocity 1.7.