Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof check in EL expression language

Tags:

instanceof

jsf

el

Is there a way to perform an instanceof check in EL?

E.g.

<h:link rendered="#{model instanceof ClassA}">           #{errorMessage1} </h:link> <h:link rendered="#{model instanceof ClassB}">           #{errorMessage2} </h:link> 
like image 597
Francesco Avatar asked Apr 25 '12 10:04

Francesco


2 Answers

You could compare Class#getName() or, maybe better, Class#getSimpleName() to a String.

<h:link rendered="#{model['class'].simpleName eq 'ClassA'}">           #{errorMessage1} </h:link> <h:link rendered="#{model['class'].simpleName eq 'ClassB'}">           #{errorMessage2} </h:link> 

Note the importance of specifying Object#getClass() with brace notation ['class'] because class is a reserved Java literal which would otherwise throw an EL exception in EL 2.2+.

The type safe alternative is to add some public enum Type { A, B } along with public abstract Type getType() to the common base class of the model.

<h:link rendered="#{model.type eq 'A'}">           #{errorMessage1} </h:link> <h:link rendered="#{model.type eq 'B'}">           #{errorMessage2} </h:link> 

Any invalid values would here throw an EL exception during runtime in EL 2.2+.

In case you're using OmniFaces, since version 3.0 you could use #{of:isInstance()}.

<h:link rendered="#{of:isInstance('com.example.ClassA', model)}">           #{errorMessage1} </h:link> <h:link rendered="#{of:isInstance('com.example.ClassB', model)}">           #{errorMessage2} </h:link> 
like image 157
BalusC Avatar answered Sep 20 '22 15:09

BalusC


That doesn't work in EL. Use the backing bean for this:

public class MyBean {      public boolean getIsClassA() {         if(model instanceof ClassA) {             return true;         }         return false;     }   } 

And then do the check by calling the backing bean:

<h:link outcome="#{PageNameA}?faces-redirect=true&amp;" rendered="#{myBean.isClassA}">           #{errorMessage} </h:link> 

like image 22
flash Avatar answered Sep 19 '22 15:09

flash