如何使用 JSF2 处理多态性?
我需要显示/编辑多态实体.
I need to display/edit polymorphic entities.
我的抽象类是Person.我的具体课程是 PhysicalPerson 和 MoralPerson
My abstract class is Person. My concrete classes are PhysicalPerson and MoralPerson
每个具体类都有自己的自定义属性.
Each concrete class has its own custom attributes.
如何根据实体类使用合适的显示/编辑(复合)组件?
How can I use the appropriate display/edit (composite) component according to entity class ?
谢谢!:)
推荐答案
EL中没有instanceof
这样的东西.但是,您可以(ab)使用 Object#getClass()
并访问 Class
在 EL 中也是如此.然后只需在组件的 rendered
属性中确定结果即可.
There is no such thing as instanceof
in EL. You can however (ab)use Object#getClass()
and access the getters of Class
in EL as well. Then just determine the outcome in the component's rendered
attribute.
<h:panelGroup rendered="#{entity.class.name == 'com.example.PhysicalPerson'}">
<p>According to Class#getName(), this is a PhysicalPerson.</p>
</h:panelGroup>
<h:panelGroup rendered="#{entity.class.simpleName == 'MoralPerson'}">
<p>According to Class#getSimpleName(), this is a MoralPerson.</p>
</h:panelGroup>
但是,自定义 EL 函数会更干净.请注意,由于 EL 中允许的属性名的严格限制,上述内容不适用于 Tomcat 7 和克隆.不再允许使用诸如 class
之类的 Java 保留字面量.你需要 #{entity['class'].name}
等等.
A custom EL function would be more clean however. Note that the above doesn't work on Tomcat 7 and clones due to extremely restrictive restrictions of allowed propertynames in EL. Java reserved literals such as class
are not allowed anymore. You'd need #{entity['class'].name}
and so on instead.
相关文章