java 复制非空对象属性值

很多时候,我们需要通过对象拷贝,比如说VO类与数据库实体bean类、更新时非空对象不更新,对同一对象不同数据分开存储等

用于对象拷贝,spring 和 Apache都提供了相应的工具类方法,BeanUtils.copyProperties

但是对于非空属性拷贝就需要自己处理了

在这里借用spring中org.springframework.beans.BeanUtils类提供的方法copyProperties(Object source, Object target, String... ignoreProperties) 

 

/**
     * 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);
 
 
 
/**
     * Copy the property values of the given source bean into the given target bean.
     * <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.
     * @param source the source bean
     * @param target the target bean
     * @param editable the class (or interface) to restrict property setting to
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
            throws BeansException {
 
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
 
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                        "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
 
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null &&
                            ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source);
                            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);
                        }
                    }
                }
            }
        }
    }


然后封装一下得到以下方法:

 

 

 

 

/**
     * @author zml2015
     * @Email zhengmingliang911@gmail.com
     * @Time 2017年2月14日 下午5:14:25
     * @Description <p>获取到对象中属性为null的属性名  </P>
     * @param source 要拷贝的对象
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
 
        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
 
    /**
     * @author zml2015
     * @Email zhengmingliang911@gmail.com
     * @Time 2017年2月14日 下午5:15:30
     * @Description <p> 拷贝非空对象属性值 </P>
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

 

 

 

测试方法就不提供了,自行测试即可

 如果项目中使用的框架有Hibernate的话,则可以通过在实体类上添加下面两条注解

@DynamicInsert(true)
@DynamicUpdate(true)

 

如果想对该注解进一步了解的话,那么可以去官网看英文文档,文档解释的很清楚,在此不再赘述了

 

https://www.mkyong.com/hibernate/hibernate-dynamic-insert-attribute-example/

文章首次发布于个人博客(吾勇士的博客)http://wuyongshi.top/articles/2017/02/14/1487063956488.html,欢迎关注我的个人博客

 

 

 
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,对象及其属性非空校验非常重要,因为如果对象属性为空,可能会导致程序崩溃或产生不可预料的错误。 以下是一些常见的Java对象及其属性非空校验方法: 1. 对象非空校验 在判断一个对象是否为空时,可以使用以下方法: ```java if (object == null) { // 对象为空 } else { // 对象不为空 } ``` 2. 字符串非空校验 在判断一个字符串是否为空时,可以使用以下方法: ```java if (str == null || str.length() == 0) { // 字符串为空 } else { // 字符串不为空 } ``` 或者使用StringUtils类中的方法: ```java if (StringUtils.isEmpty(str)) { // 字符串为空 } else { // 字符串不为空 } ``` 3. 数组非空校验 在判断一个数组是否为空时,可以使用以下方法: ```java if (array == null || array.length == 0) { // 数组为空 } else { // 数组不为空 } ``` 4. 集合非空校验 在判断一个集合是否为空时,可以使用以下方法: ```java if (collection == null || collection.isEmpty()) { // 集合为空 } else { // 集合不为空 } ``` 5. 对象属性非空校验 在判断一个对象属性是否为空时,可以使用以下方法: ```java if (object.getProperty() == null) { // 对象属性为空 } else { // 对象属性不为空 } ``` 或者使用Objects类中的方法: ```java if (Objects.isNull(object.getProperty())) { // 对象属性为空 } else { // 对象属性不为空 } ``` 以上是一些常见的Java对象及其属性非空校验方法,需要根据具体情况选择合适的方法进行校验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值