Freemarker 迭代对象的 ArrayList 并访问变量?

Freemarker iterate ArrayList of Objects and access a variable?

我有以下 POJO class:

public final class Item
{
    public final long id;
    public final String hash;

    public Item(long _id, String _hash)
    {
        id = _id;
        hash = _hash;
    }
}

我有一个 ArrayList<Item>:

ArrayList<Item> list = new ArrayList<>();
list.add(new Item(1, "abc"));
list.add(new Item(2, "def"));

列表已添加到模板:

MODEL.addAttribute("history_list", list);

模板成功遍历列表插入项目的次数但未能获得单个项目的属性:

<#list history_list as row>
     <p>${row.hash}</p>
<#else>
     no items here
</#list>

错误: 以下已评估为空或缺失: ==> row.hash [在模板 "history.ftl" 第 9 行第 69 列]

为什么?

有这样一个 mail list request 允许访问 public 字段 解决方案是使用方法 setExposeFields

DefaultObjectWrapper wrapper = new DefaultObjectWrapper(); 
wrapper.setExposeFields(true); 
FreeMarkerCfg.setObjectWrapper(wrapper); 

这在freemarker docs

中有解释

If you call setExposeFields(true) on a BeansWrapper instance, it will also expose public, non-static fields of classes as hash keys and values. I.e. if foo is a public, non-static field of the class Bar, and bar is a template variable wrapping an instance of Bar, then bar.foo expression will evaluate as the value of the field foo of the bar object. The public fields in all superclasses of the class are also exposed.

致读者

还要确保您的 class 是 public。添加来自@user7294900 答案的 wrapper.setExposeFields(true); 后,我浪费了 3 个小时。

Freemarker 不读取或访问私有 class 的 Public variables/methods 和 public class 的私有 variables/methods。