问题描述
是否可以在EL中执行instanceof
检查?
Is there a way to perform an instanceof
check in EL?
例如
<h:link rendered="#{model instanceof ClassA}">
#{errorMessage1}
</h:link>
<h:link rendered="#{model instanceof ClassB}">
#{errorMessage2}
</h:link>
推荐答案
您可以比较 Class#getName()
,或者更好的是 Class#getSimpleName()
到String
.
<h:link rendered="#{model['class'].simpleName eq 'ClassA'}">
#{errorMessage1}
</h:link>
<h:link rendered="#{model['class'].simpleName eq 'ClassB'}">
#{errorMessage2}
</h:link>
请注意使用大括号符号['class']
指定Object#getClass()
的重要性,因为class
是保留的Java文字,否则将在EL 2.2+中引发EL异常.
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+.
类型安全的替代方法是在模型的通用基类中添加一些public enum Type { A, B }
和public abstract Type getType()
.
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>
在EL 2.2+中的运行时,任何无效值都会在此引发EL异常.
Any invalid values would here throw an EL exception during runtime in EL 2.2+.
如果您使用的是 OmniFaces ,则从3.0版开始,您可以使用 #{of:isInstance()}
.
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>
这篇关于EL表达式语言中的instanceof检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!