如何使用枚举作为键遍历

如何使用枚举作为键遍历

本文介绍了Freemarker:如何使用枚举作为键遍历 Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不起作用,因为 Freemarker 似乎将 [] 中表达式的值转换为 String,然后将其用作键,这不是实际预期的.

The following code does not work because Freemarker seems to cast the value of the expression inside [] to String and then to use it as a key, which is not what is actually expected.

准备模板模型:

Map<MyEnum, Object> myMap;
myMap.put(MyEnum.FOO, "Foo");
myMap.put(MyEnum.BAR, "Bar");
templateModel.put("myMap", myMap);

我的.ftl:

<#list myMap?keys as key>
    <#assign value = myMap[key]>
    <li>${key} = ${value}</li>
</#list>

Freemarker 文档 中描述了如何访问 Enum 本身,但我没有找到关于如何使用 Enum 作为键从哈希中获取值的任何信息.

In the Freemarker documentation it is described how to access the Enum itself, but I didn't find anything about how to get a value from a hash using Enum as a key.

谢谢.

推荐答案

转述 Freemarker 文档常见问题解答对此,

您不能在 myMap[key] 表达式中使用非字符串键.可以使用方法!

因此,您可以创建一个 bean,为您提供一种访问 Java EnumMap 的方法(即).然后用你的 mapp 实例化这个 bean,并将 bean 放入你的模型中.

So, you could create a bean that provides a way for you to get to your Java EnumMap, (i.e). Then just instantiate this bean with your mapp, and put the bean in your Model.

class EnumMap
{
    HashMap<MyEnum, String> map = new HashMap<MyEnum, String>();

    public String getValue(MyEnum e)
    {
        return map.get(e);
    }
    ..constructor, generics, getters, setters left out.
}

我对您尝试实现的总体目标感到有些困惑.如果您只需要列出枚举的值(或者每个枚举的显示值).有一种更简单的方法可以做到这一点.

I'm a little bit confused about what general goal your trying to accomplish. If you just need to list out the values of the enum (or perhaps a display value for each one). There is a much easier way to do it.

我看到解决这个问题的一种方法是在 Enum 实例上放置一个显示值.

One way I've seen this problem solved is by putting a display value on the Enum instances.

enum MyEnum
{   FOO("Foo"),
    BAR_EXAMPLE("Bar Example");
    private String displayValue;

    MyEnum(String displayValue)
    {
        this.displayValue = displayValue;
    }

    public String getDisplay()
    {
        return displayValue;
    }
}

这允许您将 Enum 本身放入您的配置中,并遍历所有实例.

This allows you to put the Enum itself into your configuration, and iterate over all instances.

SimpleHash globalModel = new SimpleHash();
TemplateHashModel enumModels = BeansWrapper.getDefaultInstance().getEnumModels();
TemplateHashModel myEnumModel = (TemplateHashModel) enumModels.get("your.fully.qualified.enum.MyEnum");

globalModel.put("MyEnum", myEnumModel);
freemarkerConfiguration.setAllSharedVariables(globalModel);

然后你可以遍历枚举,

<#list MyEnum?values as item>
    ${item.display}
</#list>

这篇关于Freemarker:如何使用枚举作为键遍历 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:49