instanceof check in EL expression language
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>
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>
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&" rendered="#{myBean.isClassA}">
#{errorMessage}
</h:link>
it works:
rendered="#{node.getClass().getSimpleName() == 'Logt_anno'}"
Define a static function like:
public boolean isInstanceOf( Object obj, Class targetClass) {
return targetClass.isInstance(obj);
}
Define a custom EL function for it, and use that.
We could also pass a string name and do a forName()
inside the method.