EL 表达式语言中的 instanceof 检查 [英] instanceof check in EL expression language

查看:36
本文介绍了EL 表达式语言中的 instanceof 检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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 检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆