1. 程式人生 > >java把實體物件轉化成list和map

java把實體物件轉化成list和map

普通方式:

某一個實體有較多欄位,想把實體內的資料顯示到excel中去,但是,又不想低效率的一列一列顯示資料

所以,想把實體物件轉化成list,遍歷表格的同時顯示這個實體的資料.

下面是把實體物件轉化成list和map的方法.

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

​
package Tomap;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;

public class ToMap {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ArrayList<String> list=new ArrayList<String>();
		testmodel testmodel=new testmodel("zhangmin","nv","18");
		list=ConvertObjToMap(testmodel);
		for(int i=0;i<list.size();i++)
		{
			System.out.println(list.get(i));
		}
		/*Map<String, String> map = new HashMap<String, String>();
		for (String key : map.keySet()) {
			   System.out.println("key= "+ key + " and value= " + map.get(key));
		}*/
	}
	
	public static ArrayList ConvertObjToMap(Object obj){
        ArrayList<String> list=new ArrayList<String>();
        if (obj == null) 
         return null;
       Field[] fields = obj.getClass().getDeclaredFields();
        try {
         for(int i=0;i<fields.length;i++){
          try {
           Field f = obj.getClass().getDeclaredField(fields[i].getName());
           f.setAccessible(true);
                 Object o = f.get(obj);
                 list.add(o.toString());
          } catch (NoSuchFieldException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          } catch (IllegalArgumentException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          } catch (IllegalAccessException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
         }
        } catch (SecurityException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } 
        return list;
       }
	
	//將javabean實體類轉為map型別,然後返回一個map型別的值
    public static HashMap<String, Object> beanToMap(Object obj) { 
    	HashMap<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 (!"class".equals(name)) { 
                        params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
                    } 
                } 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
            return params; 
    }

}

​

其他方式,使用dozer可是實現map list 實體 dto 之間的相互轉化

參見地址:

http://blog.csdn.net/zhangxiaomin1992/article/details/60757406