反射

使用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反射应用的详细内容,更多请关注自学java网其它相关文章!

声明:有的资源均来自网络转载,版权归原作者所有,如有侵犯到您的权益 请联系邮箱:our333@126.com我们将配合处理!

原文地址:java反射应用发布于2021-11-26 11:17:47