java把实体对象转化成list和map

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangxiaomin1992/article/details/51646346

普通方式:

某一个实体有较多字段,想把实体内的数据显示到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

 

展开阅读全文

没有更多推荐了,返回首页