自己写的两个方法,关于bean和map的转化,比网上的效率快很多

来源:互联网 发布:淘宝装修图片 编辑:程序博客网 时间:2024/05/01 21:13
/**

* @Title: convertMap
* @Description: 使用泛型Map转bean
* 首先先把传入的实体bean的类型通过反射实例化,获取该bean的所有方法。
* 遍历map的所有的key,将key首字母变大写,前缀添加set,得到方法名
* 然后遍历bean的所有方法,如果有方法名和map的可以拼接的方法名一致,
* 就将map的value插入bean中(前提是类型必须是一致,否则报错)
* @param @param <T>
* @param @param map
* @param @param tc
* @param @return
* @param @throws IllegalArgumentException
* @param @throws IllegalAccessException
* @param @throws InvocationTargetException
* @param @throws SecurityException
* @param @throws NoSuchMethodException
* @param @throws InstantiationException 设定参数
* @return T 返回类型
* @since  1.0.0
* @author HuYiDong
* @throws
*/
public static <T> T  convertMap(Map map, Class<T> tc) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException{
T t = tc.newInstance();
Iterator it=map.entrySet().iterator();
Method [] methods=tc.getDeclaredMethods();
while(it.hasNext()){ 
Map.Entry entry=(Map.Entry)it.next();
String methodName="set"+BeantoMap.fristToUpperCase(entry.getKey().toString());
for(Method method:methods){
if(method.getName().equals(methodName)){
Object value=entry.getValue();
method.invoke(t, value);
break;
}
}
}
return t;
}
/**

* @Title: fristToUpperCase
* @Description: 首字母变大写
* @param @param str
* @param @return 设定参数
* @return String 返回类型
* @since  1.0.0
* @author HuYiDong
* @throws
*/
public static String fristToUpperCase(String str){
str=str.substring(0,1).toUpperCase()+str.substring(1,str.length());
return str;
}
/**

* @Title: fristToUpperCase
* @Description: 首字母变小写
* @param @param str
* @param @return 设定参数
* @return String 返回类型
* @since  1.0.0
* @author HuYiDong
* @throws
*/
public static String fristToLowerCase(String str){
str=str.substring(0,1).toLowerCase()+str.substring(1,str.length());
return str;
}



/**

* @Title: convertBean
* @Description: 实体bean转成Map
* 遍历对象所有方法
* 获取实体bean中get的方法,使用反射的获取方法返回值,如果值不为空,就为map的value,
* 然后把get方法去除get的部分,首字母变小写,为map的key
* @param @param obj
* @param @return
* @param @throws IllegalArgumentException
* @param @throws IllegalAccessException
* @param @throws InvocationTargetException 设定参数
* @return Map 返回类型
* @since  1.0.0
* @author HuYiDong
* @throws
*/
public static Map convertBean(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Class cla=obj.getClass();
Method [] methods=cla.getDeclaredMethods();
Map map =new HashMap();
for(Method method: methods){
if(method.getName().startsWith("get")){
String name=method.getName().substring(3,method.getName().length());
String key =BeantoMap.fristToLowerCase(name);
Object value = method.invoke(obj);
if(null!=value)map.put(key, value);
}
}
return map;
}
1 0
原创粉丝点击