Search code examples
jsfenumsomnifaces

Iterate over enum values imported by <o:importConstants>


Is it possible to iterate over ENUM in ui:repeat or c:forEach ? I'm using o:importConstants of Omnifaces 2.5.

Example code:

<o:importConstants type="my.package.MyEnum"></o:importConstants>
<c:forEach var="icon" items="#{MyEnum}">
    #{icon.toString()}
</c:forEach>

but it comes:

com.sun.faces.facelets.tag.jstl.core.MappedValueExpression$Entry@565a5787

com.sun.faces.facelets.tag.jstl.core.MappedValueExpression$Entry@6c01f0ce

com.sun.faces.facelets.tag.jstl.core.MappedValueExpression$Entry@2cd6ac37

com.sun.faces.facelets.tag.jstl.core.MappedValueExpression$Entry@7b6d8d37

com.sun.faces.facelets.tag.jstl.core.MappedValueExpression$Entry@7f8f1bb2

Solution

  • The <o:importConstants> converts the enum values to a Map<String, E> where the map key is the string representation of the enum name and the map value is the actual enum instance itself. What you're essentially attempting right now is printing each Map.Entry instance as string. You should actually be using its getKey() and/or getValue() methods instead.

    Iterating over a Map directly is as of now only supported in <c:forEach>. See also How to use jstl foreach directly over the values of a map?

    <c:forEach items="#{MyEnum}" var="entry">
        Map key: #{entry.key} <br/>
        Map value: #{entry.value} <br/>
    </c:forEach>
    

    The <ui:repeat> (and <h:dataTable>) only supports it from JSF 2.3 on. Until then, you'd best iterate over Map#values() instead.

    <ui:repeat value="#{MyEnum.values()}" var="value">
        Map value: #{value} <br/>
    </ui:repeat>