zoukankan      html  css  js  c++  java
  • 类拷贝

    业务上,有model和entity之分,但他们之间的成员变量名大多相同,所以,在做数据更新时,如果一个一个的GS会很麻烦,还好Spring有一个叫做BeanUtil的工具包可用,但是它所拷贝的,是只要名字相同就值替换,但是有时候我只需要将新值覆盖原值即可,空值不操作,所以就仿写了一份:

    public class BeanUtils extends org.springframework.beans.BeanUtils {
    
        private BeanUtils() {
        }
    
        /**
         * 实体类复制,只复制非空字段
         *
         * @param source 源类
         * @param target 目标类
         */
        public static void copyNullProperties(Object source, Object target) {
            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) {
                Method writeMethod = targetPd.getWriteMethod();
                try {
                    if (writeMethod != null) {
                        PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                        if (sourcePd != null) {
                            Method readMethod = sourcePd.getReadMethod();
                            if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (null == value) continue;
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                        }
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                }
            }
        }
    }
  • 相关阅读:
    10.16(day54)
    10.17(day55)
    10.15(day53)
    10.14(day52)
    10.12(day51)
    10.11(day50)form表单,css的引入,css选择器,css修改字体属性
    10.10(day49)初识前端,html基础
    9.25(day44)
    9.24(day43)
    9.23(day42)数据库的配置,数据库表的引擎,数据类型,约束条件
  • 原文地址:https://www.cnblogs.com/SummerinShire/p/11104148.html
Copyright © 2011-2022 走看看