Copy specific fields by using BeanUtils.copyProperties?

前端 未结 5 1800
执笔经年
执笔经年 2020-12-12 14:13

springframework.beans.BeanUtils is very useful to copy objects, and I use the \"ignoreProperties\" option frequently. However, sometimes I want to copy only spe

相关标签:
5条回答
  • 2020-12-12 14:27

    Check this out: BeanPropertyCopyUtil.

    Example:

    copyProperties(user, systemUser, "first firstName", "last lastName");
    

    You'll also need Apache Commons BeanUtils.

    0 讨论(0)
  • 2020-12-12 14:40

    Here is an Example with Spring BeanUtils class:

    public static void copyList(List sourceList,
            List targetList, Class targetType) {
    
        try {
    
            for (Object source : sourceList) {
                Object target = null;
                target = targetType.newInstance();
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            }
    
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-12-12 14:42

    If you don't want to use Commons BeanUtils you can still use Spring by using the BeanWrapper.

    You will have to manually loop through all the properties so you will want to make a static helper method.

    You can always just copy what copyProperties is doing and adjust to your liking: http://tinyurl.com/BeanUtils-copyProperties

    0 讨论(0)
  • 2020-12-12 14:45

    You can use the BeanWrapper technology. Here's a sample implementation:

    public static void copyProperties(Object src, Object trg, Iterable<String> props) {
    
        BeanWrapper srcWrap = PropertyAccessorFactory.forBeanPropertyAccess(src);
        BeanWrapper trgWrap = PropertyAccessorFactory.forBeanPropertyAccess(trg);
    
        props.forEach(p -> trgWrap.setPropertyValue(p, srcWrap.getPropertyValue(p)));
    
    }
    

    Or, if you really, really want to use BeanUtils, here's a solution. Invert the logic, gather excludes by comparing the full property list with the includes:

    public static void copyProperties2(Object src, Object trg, Set<String> props) {
        String[] excludedProperties = 
                Arrays.stream(BeanUtils.getPropertyDescriptors(src.getClass()))
                      .map(PropertyDescriptor::getName)
                      .filter(name -> !props.contains(name))
                      .toArray(String[]::new);
    
        BeanUtils.copyProperties(src, trg, excludedProperties);
    }
    
    0 讨论(0)
  • 2020-12-12 14:46

    You may use org.springframework.beans.BeanUtils.copyProperties(Object source, Object target, Class editable) throws BeansException

    Ensure the target implements the interface editable which defines the properties which would be copied.

    0 讨论(0)
提交回复
热议问题