1. 程式人生 > >javabean實體類物件轉為Map型別物件的方法

javabean實體類物件轉為Map型別物件的方法

javabean(實體類)轉Map型別
/*下面是從poi匯出EXCEL的一部分程式碼,主要將傳引數的list轉換為map型別,list裝載的資料是從資料庫取出來的,可以是陣列型別,也可以是map型別,也可以是實體類*/

public static TableData createTableData(List list,TableHeaderMetaData headMeta,String[] fields){

        TableData td = new TableData(headMeta);
        TableDataRow row = null;
        if(list != null && list.size()>0){
         if(list.get(0).getClass().isArray()){//list為陣列型別
                for (Object obj : list){
                 row = new TableDataRow(td);
              for(Object o : (Object[])obj){
         row.addCell(o);
        }
                    td.addRow(row);
                }
         }else{//JavaBean或Map型別
                for (Object obj : list){
                 row = new TableDataRow(td);
                 //判斷是//JavaBean(實體類)還是Map型別 ,如果是javaBean將呼叫 obj:beanToMap,轉為map型別
                 Map<String, Object> map = (obj instanceof Map)?(Map<String, Object>)obj:beanToMap(obj);
 
                    for(String key : fields){
                        row.addCell(map.get(key));
                    }
                    td.addRow(row);
                }
         }
        }
        return td;
}

//將javabean轉為map型別,然後返回一個map型別的值
public static Map<String, Object> beanToMap(Object obj) { 
        Map<String, Object> params = new HashMap<String, Object>(0); 
        try { 
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
            for (int i = 0; i < descriptors.length; i++) { 
                String name = descriptors[i].getName(); 
                if (!StringUtils.equals(name, "class")) { 
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
                } 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return params; 
}

放入上面方法的類需要 import java.beans.PropertyDescriptor;

需要引用兩個jar包:commons-beanutils-1.9.2.jar   commons-logging-1.2.jar

注意:

如果只引用了commons-beanutils-1.9.2.jar 未引用 commons-beanutils-1.9.2.jar,控制檯會報以下錯誤:

Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/logging/LogFactory
 at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
 at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
 at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
 at org.apache.commons.beanutils.ContextClassLoaderLocal.get(ContextClassLoaderLocal.java:153)
 at org.apache.commons.beanutils.BeanUtilsBean.getInstance(BeanUtilsBean.java:80)
 at org.apache.commons.beanutils.BeanUtils.getProperty(BeanUtils.java:382)
 at fighting.IntroSpectorDemo.main(IntroSpectorDemo.java:31)