BeanUtil複製物件非空屬性
阿新 • • 發佈:2019-01-08
開發中經常用到物件的copy,而BeanUtil工具類是大多數人copy物件的選擇.很多時候,我們在copy時,需要排除掉源物件 屬性為空的值,以免其覆蓋目標物件的值,這時候就需要把源物件中屬性為空的值找出來,工具類如下.
1.BeanUtil直接copy,可以把User物件的屬性值都copy給User1,但是這樣就把User1的nickName給覆蓋為null了
public static void main(String[] args) { User user = new User(); user.setName("李白"); user.setScore(80); User user1 = new User(); user1.setNickName("啦啦"); BeanUtil.copyProperties(user,user1); }
2.BeauUtil只copy源物件中屬性非空的值
public static void main(String[] args) { User user = new User(); user.setName("李白"); user.setScore(80); User user1 = new User(); user1.setNickName("啦啦"); BeanUtil.copyProperties(user,user1,IgnorePropertiesUtil.getNullPropertyNames(user)); }
工具類:
public class IgnorePropertiesUtil { public static String[] getNullPropertyNames(Object source) { BeanWrapper src = new BeanWrapperImpl(source); PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<>(); for (PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) emptyNames.add(pd.getName()); } return emptyNames.toArray(new String[emptyNames.size()]); } }
BeanUtil原始碼:
/**
* Copy the property values of the given source bean into the given target bean,
* ignoring the given "ignoreProperties".
* <p>Note: The source and target classes do not have to match or even be derived
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}