java使用反射机制实现map和Object对象的相互转换

使用java的反射机制实现对象和Map的相互转换

 实体类:

 


package com.test;



public class UserVo {
	private String name;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	

}

工具测试类:

/**
 * 
 */
package com.test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;

public class ObjectUtil {
	/**
	 * map转化为对象
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject(Map map, Class beanClass) throws Exception {    
        if (map == null)  
            return null;  
        Object obj = beanClass.newInstance();  
        BeanUtils.populate(obj, map);  
        return obj;  
    }
	
	//对象转换成map
	public static Map objectToMap(Object obj){
		Map map = new HashMap();
		Field[] fields = obj.getClass().getDeclaredFields();
		for(int i = 0, len = fields.length; i < len ; i++){
			String varName = fields[i].getName();
			varName = varName.toLowerCase();
			try {
				boolean accessFlag = fields[i].isAccessible();
				fields[i].setAccessible(true);
				Object o = fields[i].get(obj);
				if(o != null){
					map.put(varName, o.toString());
				}
				fields[i].setAccessible(accessFlag);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	public static void main(String[] args) {
		/*Map map =new HashMap();
		UserVo user = new UserVo();
		user.setSex("11");
		user.setName("zhuxuewen");
		map.put("sex",user.getSex() );
		map.put("name",user.getName() );
		try {
			Object object = ObjectUtil.mapToObject(map, UserVo.class);
			if(object instanceof UserVo){
				UserVo vo = (UserVo)object;
				System.out.println(vo.getName()+"  " + vo.getSex());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		UserVo user = new UserVo();
		user.setSex("11");
		user.setName("zhuxuewen");
		Map map = ObjectUtil.objectToMap(user);
		if (null!= map && map.size()!=0){
			Set> set = map.entrySet();
			for(Entry en:set){
				System.out.println(en.getKey()+"   "+en.getValue());
			}
		}
	}

}

 

jar包资源下载:

https://download.csdn.net/download/god_mycode/10647196

你可能感兴趣的:(工具类)