Map to Bean map 转 bean

package com.wen.test;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class test {


/**
* map 转 Bean
* @param mpFrom
* @param objTo
* @return
*/
public static Object mapToBean(Map mpFrom, Object objTo) {
Object[] objKeys = mpFrom.keySet().toArray();
String strFieldName = "";


try {
for (Object objkey : objKeys) {
strFieldName = objkey.toString();


Field objField = objTo.getClass().getDeclaredField(
strFieldName.toLowerCase());
objField.setAccessible(true);


objField.set(objTo, mpFrom.get(strFieldName));
}
} catch (Exception e) {
e.printStackTrace();
}
return objTo;
}


/**
* map 转 Bean 
* @param map
* @param cls
* @return
*/
public static Object map2Bean(Map map, Class cls) {
Object obj = null;
try {
obj = cls.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// 取出bean里的所有方法
Method[] methods = cls.getMethods();
for (int i = 0; i < methods.length; i++) {
// 取方法名
String method = methods[i].getName();
// 取出方法的类型
Class[] cc = methods[i].getParameterTypes();
if (cc.length != 1)
continue;


// 如果方法名没有以set开头的则退出本次for
if (method.indexOf("set") < 0)
continue;
// 类型
String type = cc[0].getSimpleName();


try {
// 转成小写
// Object value = method.substring(3).toLowerCase();
Object value = method.substring(3, 4).toLowerCase()
+ method.substring(4);
System.out.println("value == " + value);
// 如果map里有该key
if (map.containsKey(value) && map.get(value) != null) {
// 调用其底层方法
setValue(type, map.get(value), i, methods, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return obj;
}


/***************************************************************************
* 调用底层方法设置值
*/
private static void setValue(String type, Object value, int i,
Method[] method, Object bean) {
if (value != null && !value.equals("")) {
try {
if (type.equals("String")) {
// 第一个参数:从中调用基础方法的对象 第二个参数:用于方法调用的参数
method[i].invoke(bean, new Object[] { value });
} else if (type.equals("int") || type.equals("Integer")) {
method[i].invoke(bean, new Object[] { new Integer(""
+ value) });
}  else if (type.equals("double") || type.equals("Double")) {
method[i].invoke(bean, new Object[] { new Double(""
+ value) });
} else if (type.equals("float") || type.equals("Float")) {
method[i].invoke(bean, new Object[] { new Float(""
+ value) });
} else if (type.equals("long") || type.equals("Long")) {
method[i].invoke(bean,
new Object[] { new Long("" + value) });
} else if (type.equals("boolean") || type.equals("Boolean")) {
method[i].invoke(bean, new Object[] { Boolean.valueOf(""
+ value) });
} else if (type.equals("BigDecimal")) {
method[i].invoke(bean, new Object[] { new BigDecimal(""
+ value) });
} else if (type.equals("Date")) {
Date date = null;
if (value.getClass().getName().equals("java.util.Date")) {
date = (Date) value;
} else {
String format = ((String) value).indexOf(":") > 0 ? "yyyy-MM-dd hh:mm:ss"
: "yyyy-MM-dd";
SimpleDateFormat sf = new SimpleDateFormat();
sf.applyPattern(format);
date = sf.parse((String) (value));
}
if (date != null) {
method[i].invoke(bean, new Object[] { date });
}
} else if (type.equals("byte[]")) {
method[i].invoke(bean,
new Object[] { new String(value + "").getBytes() });
}
} catch (Exception e) {
System.out
.println("将linkHashMap 或 HashTable 里的值填充到javabean时出错,请检查!");
e.printStackTrace();
}
}
}



public static void main(String[] args) {
User user = new User();
Map map = new HashMap();
// map.put("userId", "123");
// map.put("userName", "userName123");
// map.put("userTel", "userTel123");
map.put("age", 234);
map.put("create", new Date());
map.put("money", new BigDecimal(123).setScale(2));
map.put("score", 23.33323);
Long start = System.currentTimeMillis();
user = (User)map2Bean(map,user.getClass());
Long end = System.currentTimeMillis();
System.out.println(" 用时 == " + (end-start));
System.out.println(user.toString());
}
}
 
  class User {


private String userId;
private Long age;
private Double score;
private Date create;


private String userName;
private BigDecimal money;


private String userTel;


public String getUserId() {
return userId;
}


public void setUserId(String userId) {
this.userId = userId;
}


public String getUserName() {
return userName;
}


public void setUserName(String userName) {
this.userName = userName;
}


public String getUserTel() {
return userTel;
}


public void setUserTel(String userTel) {
this.userTel = userTel;
}


/**
* @return the age
*/
public Long getAge() {
return age;
}


/**
* @param age the age to set
*/
public void setAge(Long age) {
this.age = age;
}


/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
System.out.println(" age="+age);
System.out.println(" userTel="+userTel);
System.out.println(" userName="+userName);
System.out.println(" userId="+userId);
System.out.println(" score="+score);
System.out.println(" create="+create);
System.out.println(" money="+money);
return super.toString();
}


/**
* @return the score
*/
public Double getScore() {
return score;
}


/**
* @param score the score to set
*/
public void setScore(Double score) {
this.score = score;
}


/**
* @return the create
*/
public Date getCreate() {
return create;
}


/**
* @param create the create to set
*/
public void setCreate(Date create) {
this.create = create;
}


/**
* @return the money
*/
public BigDecimal getMoney() {
return money;
}


/**
* @param money the money to set
*/
public void setMoney(BigDecimal money) {
this.money = money;
}


}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值