我需要顯示/編輯多態實體。如何用JSF2處理多態性?
我的抽象類是人。 我的具體類是PhysicalPerson和MoralPerson
每個具體類都有自己的自定義屬性。
如何根據實體類使用適當的顯示/編輯(複合)組件?
謝謝! :)
我需要顯示/編輯多態實體。如何用JSF2處理多態性?
我的抽象類是人。 我的具體類是PhysicalPerson和MoralPerson
每個具體類都有自己的自定義屬性。
如何根據實體類使用適當的顯示/編輯(複合)組件?
謝謝! :)
在EL中沒有這樣的東西instanceof
。然而,您可以(ab)使用Object#getClass()
並訪問EL中的獲取者Class
。然後只需確定組件的rendered
屬性中的結果。
<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}
等等。
另一種方法是創建一個基類的抽象方法,它會回報你的,你有什麼比如有的標記,並在子類中實現它,像這樣:
public abstract class Person {
public abstract boolean isPhysical();
}
public PhysicalPerson extends Person {
public boolean isPhysical() {
return true;
}
}
,然後在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>
但是,類檢查方法更通用。
這意味着每當你創建一個新的'Person'實現時,你都需要在接口/抽象類中添加一個getter。不是很有用。 – BalusC 2010-11-19 19:27:36
布爾屬性可以更改爲任何其他。但我同意,不是最美麗的解決方案。 – 2010-11-19 20:08:11