zoukankan      html  css  js  c++  java
  • Springboot 两个Bean之间转换

    import org.springframework.beans.BeansException;
    import org.springframework.beans.FatalBeanException;
    import org.springframework.util.Assert;
    
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    public class BeanCopyUtils extends org.springframework.beans.BeanUtils{
        public static void copyBean(Object source, Object target) throws BeansException {
            Assert.notNull(source, "Source must not be null");
            Assert.notNull(target, "Target must not be null");
            Class<?> actualEditable = target.getClass();  
            PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);  
            for (PropertyDescriptor targetPd : targetPds) {  
              if (targetPd.getWriteMethod() != null) {  
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());  
                if (sourcePd != null && sourcePd.getReadMethod() != null) {  
                  try {  
                    Method readMethod = sourcePd.getReadMethod();  
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {  
                      readMethod.setAccessible(true);  
                    }  
                    Object value = readMethod.invoke(source); 
                    if (value != null) {  
                      Method writeMethod = targetPd.getWriteMethod();  
                      if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {  
                        writeMethod.setAccessible(true);  
                      }  
                      writeMethod.invoke(target, value);  
                    }  
                  } catch (Throwable ex) {  
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                  }  
                }  
              }  
            } 
        } 
    }
  • 相关阅读:
    java基础 01
    c++11——模板的细节改进
    c++11——auto,decltype类型推导
    poj_1182 并查集
    poj_1988 并查集
    poj_1161 并查集
    poj_3067 树状数组
    poj_2182 线段树/树状数组
    poj_1190 树状数组
    动态规划
  • 原文地址:https://www.cnblogs.com/sunxun001/p/13085147.html
Copyright © 2011-2022 走看看