map 转换成vo_JAVAMap转换为Bean或VO
JAVAMap轉換為Bean或VO
JAVA Map 轉換為 Bean 或 VOJava.util 中的集合類包含 Java 中某些最常用的類。Map 提供了一個更通用的元素存儲方法。 Map 集合類用于存儲元素對(稱作“ 鍵”和“ 值”),其中每個鍵映射到一個值,在 java 編程中使用的相當之多。但是當我們進行業務邏輯或數據庫處理時,往往應用的是自己框架獨有的Bean 或 VO 來存儲數據,這就需要我們應用一個公共方法來將 map 中存儲的數據轉換為相對應的 Bean或 VO,主要用到技術就是 java 的反射機制。具體代碼如下該方法主要傳入的參數有兩個,第一個是 Map 接口,第二個就是要綁定的 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;參數類型String parameterType null;查找方法時需要傳入的參數Class parameterTypes new Class1;執行 invoke 方法時需要傳入的參數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;下面代碼都是參數類型是什么,如果有需求可以自行增加當 set 方法中的參數為 int 或者 IntegerifparameterTypes0 Integer.class parameterTypes0 int.classifmapValue instanceof Integerargs0 mapValue;elseargs0 Integer.parseIntStringmapValue;當 set 方法中的參數為 Dateelse ifparameterTypes0 Date.classifmapValue instanceof Dateargs0 mapValue;elseSimpleDateat sdf new SimpleDateatyyyy-MM-dd;args0 sdf.parseStringmapValue;當 set 方法中的參數為 Floatelse ifparameterTypes0 double.class parameterTypes0 Double.classifmapValue instanceof Doubleargs0 mapValue; elseargs0 Double.parseDoubleStringmapValue;當 set 方法中的參數為其他 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;執行 set 方法存儲數據.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;
總結
以上是生活随笔為你收集整理的map 转换成vo_JAVAMap转换为Bean或VO的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ORACLE ERP 系统架构与应用实践
- 下一篇: 云服务器安装kafka及python连接
