如何从Velocity模板访问对象的公共字段

Ale*_*ing 9 java velocity field public vtl

这是我的对象类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我将它添加到速度上下文中,如下所示:

Address theAddress = new Address("123 Fake St", "Springfield", "SP123");
context.put("TheAddress", theAddress);
Run Code Online (Sandbox Code Playgroud)

但是,在编写模板时,以下内容不会呈现地址字段(但是,当我将getter添加到Address类时,它可以正常工作)

<Address>
    <Line1>${TheAddress.line1}</Line1>
    <Town>${TheAddress.town}</Town>
    <Postcode>${TheAddress.postcode}</Postcode>
</Address>
Run Code Online (Sandbox Code Playgroud)

是否可以在不添加getter的情况下访问Velocity上的对象的公共字段?

Nat*_*bna 4

默认情况下不是。您需要配置不同的 Uberspect 实现。

  • 这是必要的,因为 Velocity 不支持公共字段。试试这个:http://maven-doccheck.sourceforge.net/samples/ShinobuDemo/apidocs/org/apache/velocity/tools/generic/introspection/PublicFieldUberspect.html (2认同)