您的位置:首页 > 编程语言 > Java开发

JAVA Map转换为Bean或VO

2011-03-04 17:41 302 查看
Java.util 中的集合类包含 Java 中某些最常用的类。Map 提供了一个更通用的元素存储方法。
Map 集合类用于存储元素对(称作“键”和“值”),其中每个键映射到一个值,在java编程中使用
的相当之多。但是当我们进行业务逻辑或数据库处理时,往往应用的是自己框架独有的Bean或VO来
存储数据,这就需要我们应用一个公共方法来将map中存储的数据转换为相对应的Bean或VO,主要用到
技术就是java的反射机制。具体代码如下:
//该方法主要传入的参数有两个,第一个是Map接口,第二个就是要绑定的VO。
public static void mapBind(Map map,PmsBaseVO pmsVo) throws Exception{

//获得传入vo的Class方法
Class newClass = pmsVo.getClass();
//得到vo中所有的成员变量
Field[] fs = newClass.getDeclaredFields();
//方法变量
String methodName = null;
//map的value值
Object mapValue = null;
//参数类型
String parameterType = null;
//查找方法时需要传入的参数
Class[] parameterTypes = new Class[1];
//执行invoke方法时需要传入的参数
Object[] args = new Object[1];
//取得Map的迭代器
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
//取出map的key值
String key = (String)it.next();
if(key != null){
for(int i=0;i<fs.length;i++){
if(key.equals(fs[i].getName())){
//拼set方法名
methodName = "set" + key.replaceFirst(key.substring(0, 1),key.substring(0, 1).toUpperCase());
try {
//得到vo中成员变量的类型
parameterTypes[0] = fs[i].getType();
parameterType = parameterTypes[0].toString();
//找到vo中的方法
Method method = newClass.getDeclaredMethod(methodName,parameterTypes);
mapValue = map.get(key);
//下面代码都是参数类型是什么,如果有需求可以自行增加
//当set方法中的参数为int或者Integer
if(parameterTypes[0] == Integer.class || parameterTypes[0] == int.class){
if(mapValue instanceof Integer){
args[0] = mapValue;
}else{
args[0] = Integer.parseInt((String)mapValue);
}
//当set方法中的参数为Date
}else if(parameterTypes[0] == Date.class){
if(mapValue instanceof Date){
args[0] = mapValue;
}else{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
args[0] = sdf.parse((String)mapValue);
}
//当set方法中的参数为Float
}else if(parameterTypes[0] == double.class || parameterTypes[0] == Double.class){
if(mapValue instanceof Double){
args[0] = mapValue;
}else{
args[0] = Double.parseDouble((String)mapValue);
}
//当set方法中的参数为其他
} else if( parameterTypes[0] == String.class){

if(mapValue instanceof String[]){

String[] tempArray = (String[])mapValue;
String result = "";
for(int m=0;m<tempArray.length;m++){
result = result + tempArray[m] + ",";
}
result = result.substring(0, result.length()-1);
args[0] = result;

}else{
args[0] = (String)mapValue;
}
}else {
args[0] = mapValue;
}
//执行set方法存储数据
method.invoke(pmsVo, args);

} catch (SecurityException e) {
throw new SecurityException("[mapBind]安全异常:"+ e);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("[mapBind]Vo中无此方法异常" + e);
} catch (IllegalArgumentException e) {
throw new Exception("VO中"+key+"属性类型"+parameterType+"与Map中值为"+mapValue+"的类型不匹配");
} catch (IllegalAccessException e) {
throw new IllegalAccessException("[mapBind]IllegalAccessException异常");
} catch (ParseException e) {
throw new ParseException("[mapBind]ParseException异常", 0);
}
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: