首页 > 编程语言 >Java Bean 转换(copy)

Java Bean 转换(copy)

时间:2022-08-26 16:12:01浏览次数:54  
标签:Java target Bean testEntity3 import copy public String

废话不多说上代码

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * 实现此接口让对象具有基本属性拷贝的能力
 */
public interface Copier {

    /**
     * 传入对象,对其进行属性拷贝
     *
     * @param target 拷贝目标对象
     */
    default <T> void copy(T target) {
        BeanUtils.copyProperties(this, target);
    }

    /**
     * 传入对象类型, 进行属性拷贝并且得到其对象
     *
     * @param type 对象类型 Class对象
     * @return 对象
     */
    default <T> T copy(Class<T> type) {
        T target = BeanUtils.instantiateClass(type);
        copy(target);
        return target;
    }

    /**
     * 不为null的属性值才会拷贝
     *
     * @param target 拷贝目标对象
     */
    default <T> void copyNotNull(T target) {
        BeanWrapper wrapper = new BeanWrapperImpl(this);
        PropertyDescriptor[] pds = wrapper.getPropertyDescriptors();
        Set<String> properties = new HashSet<>();
        for (PropertyDescriptor propertyDescriptor : pds) {
            String propertyName = propertyDescriptor.getName();
            Object propertyValue = wrapper.getPropertyValue(propertyName);
            if (propertyValue != null) {
                if (propertyValue instanceof String && !StringUtils.hasText((String) propertyValue)) {
                    properties.add(propertyName);
                }
            } else {
                properties.add(propertyName);
            }
        }
        BeanUtils.copyProperties(this, target, properties.toArray(new String[0]));
        properties.clear();
    }
}

让自己的实体类实现上面的类,使用方法如下:

创建俩个测试的实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity3 implements Copier {

    private Integer id;

    private String name;

    private Integer age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestEntity4 implements Copier {

    private Integer id;

    private String name;
}

测试:

public class Beanutils {
    public static void main(String[] args) {
        TestEntity3 testEntity3 = new TestEntity3();
        testEntity3.setId(1);
        testEntity3.setName("aaa");
        testEntity3.setAge(20);
        TestEntity4 copy = testEntity3.copy(TestEntity4.class);
        System.out.println(copy);
    }
}

结果:

结束!

标签:Java,target,Bean,testEntity3,import,copy,public,String
From: https://www.cnblogs.com/demolive/p/16627865.html

相关文章