我試圖構建一個模塊來管理數據庫的目錄,如:country,enterprises,users等。用戶應該選擇目錄從一個組合框和系統應該顯示一個表的主要列(數據庫中不空和一些預定義我)。從我完成的3個目標中,我只實現了2: 1.-使用反射選擇目錄後,從實體類獲得@NotNull
字段 2.使用動態列顯示錶格,也從上面檢索它們。 但是3號給我帶來麻煩。關鍵是,我用這個folling代碼在視圖中動態顯示的列(基於@NotNull
場I存儲在對象),(https://www.primefaces.org/showcase/ui/data/datatable/columns.xhtml):如何將類(java.lang.Class)轉換爲使用反射獲得的類
<p:dataTable id="conceptos" var="pojo" value="#{catalogoMB.comocombo}>
<p:columns value="#{catalogoMB.columns}" var="column"
columnIndexVar="colIndex" sortBy="#{pojo[column.property]}" filterBy="#
{pojo[column.property]}">
<f:facet name="header">
<h:outputText value="#{column.header}" />
</f:facet>
<h:outputText value="#{pojo[column.property]}" />
</p:columns>
</p:dataTable>
因此,例如,在正常的方式,無需反射上面的代碼將會像這樣工作: comocombo將具有以下屬性:name,value,id;和我的列數組將是相同的:名稱,值,ID ... 事情是,comocombo
是一個List<Object>
對象,其中我存儲字段的反射類值,它返回java.lang.class而不是EntityClass的實例儘管我設法從該類的一個對象實例中調用setter和getter(combito)-supposedly- ,所以當我嘗試顯示pojo[column.property]
-> comocombo [「id」],comocombo [「name」]或comocombo [「value」 ]它給我一個例外說java.lang.class
沒有這個任何屬性....我怎麼能達到他們?我已閱讀Map<String, String>
和.cast()
但我不確定這可能是這樣。
public void populateT(){
comocombo=new ArrayList<>();
Object tt ;
y = tabla.get(tabla.size()-1).getConcpetos(); //result of query type:
FindAll from the entity Class
try{
Class combito= Class.forName("sipe.services."+ catName); //the "path" of the
Entity Classes
for (Integer j=0; j<y.size()-1; j++){
tt=y.get(j);
for (Integer i=0; i< tabla.size()-1; i++){
tucampo=minustomayus(y.get(j).getClass().getDeclaredField(tabla.get(i).getNombre_c()).getName()); //tabla.get(i).getNombre_c()-> here I've stored the @NotNull properties' names (countryid, countryname...) whic are the same in columns = new ArrayList<ColumnModel>(); (catalogoMB.columns in the view)
Class cls= Class.forName("sipe.services."+ catName);
Method method = cls.getDeclaredMethod("get"+tucampo); // for example "countryid" -> getCountryid
Class<?> type = null;
for (Method methods : combito.getDeclaredMethods())
{ //Here I'm trying to invoke setter of the Entity Class in order to store its values..
//equivalent to: if o is an instance of Entity Class Country: Country o = new Country(); o.setCountryid(2);
if (methods.getName().contains("set"+tucampo)){
type=method.getReturnType();
methods.invoke(combito.newInstance(),method.invoke(tt));
}
}
如果我應該明白這一點,你想要根據組合框中的選定值動態加載數據表列,其中組合框的值爲enti ty類? – Kaizen
是@Kaizen,我已經達到了這個目的:動態添加列到我的數據表...根據每個實體選擇的類...當我嘗試根據這些列顯示數據時遇到問題,因爲我的對象是java。 lang.Class(反射的效果)和我的變量p:dataTable沒有達到屬性... –
你可以回答你的問題,並接受:) – Kaizen