java 通过反射完成list到beanlist再把ben转换成map的过程

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




public class Bean2MapUtil {

	private Bean2MapUtil(){}
	
	/**
	 * 把list转为beans
	 * @param result
	 * @return
	 */
	private static List<Object> toBeanList(List<List<String>> result,@SuppressWarnings("rawtypes") Class classType){
		List<Object> resulsBeans = new ArrayList<Object>();
		Object obj;
		try {
			Field[] fields = classType.getDeclaredFields();
			int i = 0;
			if(result.size()>=3){
				for(List<String> item:result){
					i++;
					if(i<=2)continue;
					obj = classType.newInstance();
					for (int j = 0; j < fields.length; j++) {
						//减三表示页面有三个隐藏域
						PropertyDescriptor pd = new PropertyDescriptor(fields[j].getName(), classType);
						Method wM = pd.getWriteMethod();//获得写方法
						wM.invoke(obj, item.get(j));//
					}
					resulsBeans.add(obj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resulsBeans;
	}
	/**
	 * 把beanlist转化为MapList
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List<Map> beans2Maps(String filePath,Class classType){
		List<Map> ret = new ArrayList<Map>();
		ReadExcel03 e03 = new ReadExcel03();//读取excel
		ReadExcel07 e07 = new ReadExcel07();
		ReadExcelAdapter adapter = new ReadExcelAdapter(filePath, e03, e07);
		List<List<String>> result = adapter.readExcel();
		List<Object> resulsBeans = toBeanList(result,classType);
		try {
			for(int i= 0;i < resulsBeans.size();i++){
				Field[] fields = classType.getDeclaredFields();
				Map<String, Object> tempMap = new HashMap<String,Object>();
				for (int j = 0; j < fields.length; j++) {
					//减三表示页面有三个隐藏域
					PropertyDescriptor pd = new PropertyDescriptor(fields[j].getName(), classType);
					Method wM = pd.getReadMethod();//获得写方法
					tempMap.put(fields[j].getName(), wM.invoke(resulsBeans.get(i)));
				}
				ret.add(tempMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
}

 

你可能感兴趣的:(java)