获取任何一个类的VO

Posted by 浮生 on 03-04,2020
package com.auth.frame.common.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName DTOVOUtil
 * @Author WFS
 * @Date 2020/1/20 16:24
 */
@Slf4j
public class DTOToVOUtil {

    @SuppressWarnings("unchecked")
    public static <T> T getVo(T c, String necessary, String exception) {
        if (necessary == null || "".equals(necessary.replaceAll(" ", ""))) {
            necessary = "";
        }
        if (exception == null || "".equals(exception.replaceAll(" ", ""))) {
            exception = "";
        }
        necessary = necessary.replaceAll(" ", "");
        exception = exception.replaceAll(" ", "");
        List<String> nl;
        List<String> e = Arrays.asList(exception.split(","));
        if ("".equals(necessary)) {
            nl = Stream.of(c.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        } else {
            nl = Arrays.asList(necessary.split(","));
        }
        List<String> n = nl.stream().filter(ele -> e.stream().noneMatch(ele::equals)).collect(Collectors.toList());
        try {
            Object cn = Class.forName(c.getClass().getName()).newInstance();
            String[] ig = Stream.of(c.getClass().getDeclaredFields()).filter(ele -> n.stream().noneMatch(ele.getName()::equals)).map(Field::getName).toArray(String[]::new);
            BeanUtils.copyProperties(c, cn, ig);
            return (T) cn;
        } catch (Exception exp) {
            log.error("获取VO失败", exp);
            return null;
        }
    }
}

使用说明

  参数necessary是一个字符串,如果是null或者""则默认包含所有,exception 过滤的字符串,如果为null或者"",则不过滤。比如:实体A,包含namevalue, id三个属性,getVo(A, "name", null),则获得一个只有name值的A;getVo(A, null, "value,id")获得相同的结果;getVo(A, null, "name, value"),获得一个A,且把A的属性namevalue置为null。