JAVA反射应用

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_39416311/article/details/82788281

 使用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);
    }

 

展开阅读全文

没有更多推荐了,返回首页