Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to testing for enum equality in JSF?

Tags:

enums

jsf

el

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}"/> 
like image 497
DD. Avatar asked Mar 26 '10 15:03

DD.


People also ask

Can you use == for enum?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can we compare enum with equals ()?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.


1 Answers

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}" /> 
like image 64
BalusC Avatar answered Sep 19 '22 22:09

BalusC