Class copy

On business, model and entity of the points, but the member variable name between them are mostly the same, so when doing data update, if a one GS will be difficult, but fortunately there is a tool called Spring BeanUtil package is available, but it copied, as long as the same name on the replacement value, but sometimes I just need to cover the new value to the original value, null value does not operate, so it parodies a:

public class BeanUtils extends org.springframework.beans.BeanUtils {

    private BeanUtils() {
    }

    /**
     * Entity class copy, copy only non-empty field
     *
     * @Param Source source class
     * @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 {
                 os (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);
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/SummerinShire/p/11104148.html