反射
使用JAVA反应进行两个vo有相同字段名字进行子转换:
@Test public void doTransTest() { A a= new A(); A.setC(111L); B b= new B(); doTrans(a, b); } /** *@param sour 来源vo *@param dest 待转换vo */ public void doTrans(Object sour, Object dest) { if (sour == null) { dest = null; return; } //反射原理应用 Class<?> sourceClass = sour.getClass(); Class<?> destClass = dest.getClass(); for (Field field : sourceClass.getDeclaredFields()) { String fieldName = field.getName(); Object value; if (fieldName.equals("serialVersionUID")) { continue; } try { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, sourceClass); value = propertyDescriptor.getReadMethod().invoke(sour); } catch (Exception e) { //log continue; } if (value == null) { continue; } try { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, destClass); propertyDescriptor.getWriteMethod().invoke(dest, value); } catch (Exception e) { //log continue; } } }
SpringIOC反射的应用:
/** * springIOC和反射test * * @throws Exception */ @Test public void reflexTest() throws Exception { /** * 第一步,springIOC解析如下bean * <bean id="cartBean" class="com.mmall.pojo.Cart"></bean> */ //解析bean字符串xxxxx String beanId = "cartBean"; String beanClass = "com.mmall.pojo.Cart"; Class<?> cls = Class.forName(beanClass); Object object = cls.newInstance(); //模拟spring容器 Map container = Maps.newHashMap(); //bean注入spring容器,实例化成功 container.put(beanId, object); /** * 第二步:模拟ref注入 * <bean id="cartBean" class="com.mmall.pojo.Cart"></bean> * <property name="user" ref="userBean"></property> * <bean> */ //初始化refBean(userBean) String beanIdUser = "cartBean"; String beanClassUser = "com.mmall.pojo.User"; Class<?> clsUser = Class.forName(beanClassUser); Object objectUser = clsUser.newInstance(); //并注入spring容器 container.put(beanIdUser,objectUser); //得到cartBean的setUser方法 String setUserName = "setUser"; Object paramBean = container.get(beanIdUser); //cls是cart对象 Method setter = cls.getMethod(setUserName, objectUser.getClass()); //注入set方法 setter.invoke(object, paramBean); }
以上是java反射应用的详细内容。更多信息请关注PHP中文网其他相关文章!