All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.feizns.bean.BeanUtils Maven / Gradle / Ivy

Go to download

Java 类型,反射,属性以及实体类操作工具类。

There is a newer version: 5.5-RELEASE
Show newest version
package com.gitee.feizns.bean;

import com.gitee.feizns.StreamUtils;
import com.gitee.feizns.reflect.ConstructorUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * java com.gitee.feizns.bean.
 * @author feizns
 * @since 2019/6/9 0009
 */
public abstract class BeanUtils {

    /**
     * 复制属性
     * @param target
     * @param source
     * @param 
     * @return
     */
    public static final  T copyProperties(T target, Object... source) {
        return copyProperties(target, StreamUtils::noChangeFun, source);
    }

    /**
     * 复制属性
     * @param target
     * @param source
     * @param 
     * @return
     */
    public static final  T copyProperties(T target, Function keyMap, Object... source) {
        Map> map = PropertyUtils.writableProps(target)
                .collect(Collectors.toMap(Property::name, item -> item, StreamUtils::leaveSecond, LinkedHashMap::new));
        for (Object o : source) {
            PropertyUtils.readableProps(o).forEach(prop -> {
                String newKey = keyMap.apply(prop.name());
                Property property = map.get(newKey);
                if ( property != null )
                    property.set(prop.val());
            });
        }
        return target;
    }

    /**
     * 新创建一个对象复制属性
     * @param targetType
     * @param source
     * @param 
     * @return
     */
    public static final  T copyProperties(Class targetType, Object... source) {
        return copyProperties(ConstructorUtils.newInstance(targetType), source);
    }

    /**
     * 新创建一个对象复制属性
     * @param targetType
     * @param source
     * @param 
     * @return
     */
    public static final  T copyProperties(Class targetType, Function keyMap, Object... source) {
        return copyProperties(ConstructorUtils.newInstance(targetType), keyMap, source);
    }

}