map 转换成vo_JAVAMap转换为Bean或VO
JAVAMap轉(zhuǎn)換為Bean或VO
JAVA Map 轉(zhuǎn)換為 Bean 或 VOJava.util 中的集合類包含 Java 中某些最常用的類。Map 提供了一個(gè)更通用的元素存儲(chǔ)方法。 Map 集合類用于存儲(chǔ)元素對(duì)(稱作“ 鍵”和“ 值”),其中每個(gè)鍵映射到一個(gè)值,在 java 編程中使用的相當(dāng)之多。但是當(dāng)我們進(jìn)行業(yè)務(wù)邏輯或數(shù)據(jù)庫處理時(shí),往往應(yīng)用的是自己框架獨(dú)有的Bean 或 VO 來存儲(chǔ)數(shù)據(jù),這就需要我們應(yīng)用一個(gè)公共方法來將 map 中存儲(chǔ)的數(shù)據(jù)轉(zhuǎn)換為相對(duì)應(yīng)的 Bean或 VO,主要用到技術(shù)就是 java 的反射機(jī)制。具體代碼如下該方法主要傳入的參數(shù)有兩個(gè),第一個(gè)是 Map 接口,第二個(gè)就是要綁定的 VO。public static void mapBindMap map,PmsBaseVO pmsVo throws Exception獲得傳入 vo 的 Class 方法Class newClass pmsVo.getClass;得到 vo 中所有的成員變量Field fs newClass.getDeclaredFields;方法變量String Name null;map 的 value 值Object mapValue null;參數(shù)類型String parameterType null;查找方法時(shí)需要傳入的參數(shù)Class parameterTypes new Class1;執(zhí)行 invoke 方法時(shí)需要傳入的參數(shù)Object args new Object1;取得 Map 的迭代器Iterator it map.keySet.iterator;while it.hasNext 取出 map 的 key 值String key Stringit.next; ifkey nullforint i0;ifs.length;iifkey.equalsfsi.getName拼 set 方法名Name set key.replaceFirstkey.substring0, 1,key.substring0, 1.toUpperCase;try 得到 vo 中成員變量的類型parameterTypes0 fsi.getType;parameterType parameterTypes0.toString;找到 vo 中的方法 newClass.getDeclaredName,parameterTypes;mapValue map.getkey;下面代碼都是參數(shù)類型是什么,如果有需求可以自行增加當(dāng) set 方法中的參數(shù)為 int 或者 IntegerifparameterTypes0 Integer.class parameterTypes0 int.classifmapValue instanceof Integerargs0 mapValue;elseargs0 Integer.parseIntStringmapValue;當(dāng) set 方法中的參數(shù)為 Dateelse ifparameterTypes0 Date.classifmapValue instanceof Dateargs0 mapValue;elseSimpleDateat sdf new SimpleDateatyyyy-MM-dd;args0 sdf.parseStringmapValue;當(dāng) set 方法中的參數(shù)為 Floatelse ifparameterTypes0 double.class parameterTypes0 Double.classifmapValue instanceof Doubleargs0 mapValue; elseargs0 Double.parseDoubleStringmapValue;當(dāng) set 方法中的參數(shù)為其他 else if parameterTypes0 String.classifmapValue instanceof StringString tempArray StringmapValue;String result ;forint m0;mtempArray.length;mresult result tempArraym ,;result result.substring0, result.length-1;args0 result;elseargs0 StringmapValue;else args0 mapValue;執(zhí)行 set 方法存儲(chǔ)數(shù)據(jù).invokepmsVo, args; catch SecurityException e throw new SecurityExceptionmapBind安全異常 e; catch NoSuchException e throw new NoSuchExceptionmapBindVo 中無此方法異常 e; catch IllegalArgumentException e throw new ExceptionVO 中key屬性類型parameterType與 Map 中值為mapValue的類型不匹配; catch IllegalAccessException e throw new IllegalAccessExceptionmapBindIllegalAccessException 異常; catch ParseException e throw new ParseExceptionmapBindParseException 異常, 0;
總結(jié)
以上是生活随笔為你收集整理的map 转换成vo_JAVAMap转换为Bean或VO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ORACLE ERP 系统架构与应用实践
- 下一篇: 相控阵天线有源驻波测试