All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kedauis.util.BeanUtil Maven / Gradle / Ivy

The newest version!
package com.kedauis.util;

import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * author linyong
 * descriptione 针对bean处理常用方法
 * date 20171025
 * time 14:12
 */
@Component
public class BeanUtil {
    /**
     * author linyong
     * date 2017/10/10
     * time 14:49
     * descriptione 将一个Bean赋值给另一个Bean
     * @param from 源
     * @param to 目标
     */
    public static void convertBean2Bean(Object from, Object to) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(to.getClass());
            PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();
            Class classType = from.getClass();
            for (PropertyDescriptor p : ps) {
                Method getMethod = p.getReadMethod();
                Method setMethod = p.getWriteMethod();
                if (getMethod != null && setMethod != null) {
                    try {
                        Method fromGetMethod = classType.getMethod(getMethod.getName());
                        Object result = fromGetMethod .invoke(from);
                        setMethod.invoke(to, result);
                    } catch (Exception e) {
                        // 如果from没有此属性的get方法,跳过
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author linyong
     * date 2017/10/10
     * time 14:49
     * descriptione 将一个Bean赋值给另一个Bean
     * @param from 源
     * @param to 目标
     * @return result bean
     */
    public static Object convertBean(Object from, Object to) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(to.getClass());
            PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();
            Class classType = from.getClass();
            for (PropertyDescriptor p : ps) {
                Method getMethod = p.getReadMethod();
                Method setMethod = p.getWriteMethod();
                if (getMethod != null && setMethod != null) {
                    try {
                        Method fromGetMethod = classType.getMethod(getMethod.getName());
                        Object result = fromGetMethod .invoke(from);
                        setMethod.invoke(to, result);
                    } catch (Exception e) {
                        // 如果from没有此属性的get方法,跳过
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return to;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy