java实现的bean类型和map类型相互转换的工具类

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;




/**
 * @author Ms
 * @version 2014-06-12
 * @see 将对象和Map之间相互转换的工具类
 * */
public class BeanMapExchange {


/**
* @see map转换成bean
* @param map要转换的map
* @param thisOgj 转换后的bean
* */
public static void mapToBean(Map map,Object thisObj)throws Exception{
Set set = map.keySet();  
Iterator iterator = set.iterator();
while(iterator.hasNext()){
Object obj = iterator.next();
   Object val = map.get(obj);  
   setMethod(obj, val, thisObj);
}

}

/**
* @author Ms
* @see 向bean注入属性
* @param method 属性名,需要与bean里的属性名称保持一致(区分大小写)
* @param value 向属性注入的值,需要与bean里的属性类型保持一致
* @param thisObj bean对象
* */
public static void setMethod(Object method, Object value ,Object thisObj) throws Exception{  
   Class c;  
   try  
   {  
     //建立类
     c = Class.forName(thisObj.getClass().getName());  
     //解析方法名
     String met = (String) method;  
     met = met.trim();  
     if (!met.substring(0, 1).equals(met.substring(0, 1).toUpperCase()))  
     {  
       met = met.substring(0, 1).toUpperCase() + met.substring(1);  
     }  
     if (!String.valueOf(method).startsWith("set"))  
     {  
       met = "set" + met;  
     }  
     Class types[] = new Class[1];
     //获取该属性的类型
     Field type=c.getField((String) method);
     types[0] = Class.forName(type.getType().getName());
     //获取方法
     Method m = c.getMethod(met, types);
     //注入参数值
     m.invoke(thisObj, value);
   }  
   catch (Exception e)  
   {  
     e.printStackTrace();  
     throw e;
   }  
 }
/**
* @see 将bean类型转换成Map输出

* */
public static Map beanToMap(Object thisObj)  
 {  
   Map map = new HashMap(); 
   Class c;  
   try  
   {  
     c = Class.forName(thisObj.getClass().getName());  
     Field[] fields=c.getFields();
     for(Field field:fields){
     String fieldName=field.getName();
     String method="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
     Method m = c.getMethod(method,null);
     try {
     Object value = m.invoke(thisObj);
     if(value==null){
     map.put(fieldName, "");
     }else{
     map.put(fieldName, value);
     }
} catch (Exception e) {
e.printStackTrace();
return map;
}
     }
   }  
   catch (Exception e)  
   {  
     e.printStackTrace();
     return map;
   }  
   return map;  
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值