How to testing for enum equality in JSF?

JsfEnumsEl

Jsf Problem Overview


Is it possible to test for enum equality in JSF?

E.g. where stuff is an enum Stuff:

<h:outputText value="text" rendered="#{mrBean.stuff == mrsBean.stuff}"/>

Jsf Solutions


Solution 1 - Jsf

This is actually more EL related than JSF related. The construct as you posted is valid, but you should keep in mind that enum values are in EL 2.1 are actually evaluated as String values. If String.valueOf(mrBean.getStuff()) equals String.valueOf(mrsBean.getStuff()), then your code example will render. In EL 2.2 the same construct will work, but they are evaluated as true enums.

Note that it indeed requires a getter method to return the enum value. Given the fact that enums are treated as String, you can in essence also just do:

<h:outputText value="text" rendered="#{mrBean.stuff == 'FOO'}" />

In current EL 2.2 version, you cannot access enum values directly like this:

<h:outputText value="text" rendered="#{mrBean.stuff == Stuff.FOO}" />

This is only possible when you use OmniFaces <o:importConstants>:

<o:importConstants type="com.example.Stuff" />
...
<h:outputText value="text" rendered="#{mrBean.stuff == Stuff.FOO}" />

Solution 2 - Jsf

If you have the enum

public enum Status {
    YES, NO
}

you can reference the enums in your jsf pages like so:

<h:outputText value="text" rendered="#{myBean.status == 'YES'}"/>

I'm not so sure about the String evaluation, due to something I stumbled upon while refactoring some code to use enums: if you have a typo in your status String, ie:

<h:outputText value="text" rendered="#{myBean.status == 'YESSIR'}"/>

you will actually get a runtime error when you hit the page because the EL parser will try to coerce 'YESSIR' into a Status enum and fail.

Solution 3 - Jsf

You could define testing methods on the enum, see the following source.

Enum definition:

public enum MyEnum {
    FOO;
    public boolean isFoo(){
        return FOO.equals(this);
    }
}

JSF code:

<h:outputText value="text" rendered="#{mrBean.stuff ne null and mrBean.stuff.foo}"/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDD.View Question on Stackoverflow
Solution 1 - JsfBalusCView Answer on Stackoverflow
Solution 2 - JsfNaganalfView Answer on Stackoverflow
Solution 3 - JsfPavel SedekView Answer on Stackoverflow