How to access an object's public fields from a Velocity template

11,370

Solution 1

Not by default. You need to configure a different Uberspect implementation.

Solution 2

The Velocity user guide suggests it's not possible. Quote:

[Velocity] 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

  1. getaddress()
  2. getAddress()
  3. get("address")
  4. isAddress()

For upper-case property names like $customer.Address, it is slightly different:

  1. getAddress()
  2. getaddress()
  3. get("Address")
  4. isAddress()
Share:
11,370
Alex Spurling
Author by

Alex Spurling

Updated on July 20, 2022

Comments

  • Alex Spurling
    Alex Spurling almost 2 years

    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?

  • Alex Spurling
    Alex Spurling about 11 years
    Could you add any details such as link to documentation on how to do this or on why this is neccessary?
  • Scott
    Scott about 11 years
    It's necessary because Velocity doesn't support public fields. Try this out: maven-doccheck.sourceforge.net/samples/ShinobuDemo/apidocs/o‌​rg/…
  • evanmcdonnal
    evanmcdonnal about 8 years
    It's brilliant that they implement their framework according to convention rather than actual language rules...