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>
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>
There is a way, see
JSF EL: instanceof reserved but not yet implemented?
However, the
instanceof
operator is still not implemented, at least in Mojarra 2.1. Please vote for the bug here:http://java.net/jira/browse/JSP_SPEC_PUBLIC-113
The best workaround currently is probably to store the class name in a backing bean getter instead of creating a boolean test method for each class:
So it would be a mix of BalusC's and flash's solutions. It would however be much more readable in JSF than BalusC's plus it pretty much resembles the future
instanceof
operator use:This will not produce one method per class test on the backing bean as flash suggested. This could be slower than flash's though.
it works:
You could compare
Class#getName()
or, maybe better,Class#getSimpleName()
to aString
.Note the importance of specifying
Object#getClass()
with brace notation['class']
becauseclass
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 withpublic abstract Type getType()
to the common base class of the model.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()}
.Define a static function like:
Define a custom EL function for it, and use that. We could also pass a string name and do a
forName()
inside the method.That doesn't work in
EL
. Use the backing bean for this:And then do the check by calling the backing bean:
You could use a helper bean for that:
Usage:
This has the advantage that inheritance is taken into account and you can test for classes which you can't modify (both disadvantages of the solutions of BalusC).
If you like to use the simple class name (and don't fear name clashes), you could use a lookup map which you fill by hand or with a class path scanner like org.reflections:
You could even move the helper function to an ELResolver:
Usage: