How to handle polymorphism with JSF2?

女生的网名这么多〃 提交于 2019-12-09 00:39:25

问题


I need to display/edit polymorphic entities.

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 ?

Thanks ! :)


回答1:


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>

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.




回答2:


Another way is to create an abstract method in a base class, which will return you some mark of what instance you have, and implement it in your subclasses, like this:

public abstract class Person {

public abstract boolean isPhysical();

}

public PhysicalPerson extends Person {

public boolean isPhysical() {
     return true;
}

}

and then in jsf:

<h:panelGroup rendered="#{entity.physical}">
    <p>this is a PhysicalPerson.</p>
</h:panelGroup>
<h:panelGroup rendered="#{ not entity.physical}">
    <p>this is a Moral Person.</p>
</h:panelGroup>

However the class checking approach is more universal.



来源:https://stackoverflow.com/questions/4166247/how-to-handle-polymorphism-with-jsf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!