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

com.soento.core.util.BeanUtil Maven / Gradle / Ivy

package com.soento.core.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ContextClassLoaderLocal;

import java.util.ArrayList;
import java.util.List;

/**
 * @author soento
 */
public final class BeanUtil extends BeanUtils {

    private static final ContextClassLoaderLocal BEANS_BY_CLASSLOADER_EXT = new ContextClassLoaderLocal() {
        @Override
        protected BeanUtilBean initialValue() {
            return new BeanUtilBean();
        }
    };

    private static BeanUtilBean getInstance() {
        return (BeanUtilBean) BEANS_BY_CLASSLOADER_EXT.get();
    }

    public static  T newInstance(Class clazz) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static  T newInstance(String className) {
        try {
            return (T) newInstance(Class.forName(className));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void copy(Object origin, Object destination, boolean isRecursive) {
        try {
            getInstance().copyProperties(destination, origin, isRecursive);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void copy(Object origin, Object destination) {
        copy(origin, destination, true);
    }


    /**
     * 对象构建
     *
     * @param origin 拷贝源
     * @param clazz  目标类
     * @param     目标类泛型
     * @return 结果对象
     */
    public static  T build(Object origin, Class clazz) {
        if (origin == null) {
            return null;
        }
        T destination = newInstance(clazz);
        copy(origin, destination);
        return destination;
    }

    /**
     * 对象构建
     *
     * @param fromList 拷贝源
     * @param clazz    目标类
     * @param       目标类泛型
     * @return 结果对象
     */
    public static  List buildList(List fromList, Class clazz) {
        if (CollectionUtil.isEmpty(fromList)) {
            return null;
        }
        List resultList = new ArrayList<>();
        for (Object from : fromList) {
            resultList.add(build(from, clazz));
        }
        return resultList;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy