Java对象操作工具类

public class BeanUtil {

    public static <T> List<T> copyProp(List<?> fromList, Class<T> toC, String... filterProp)  {
        List<T> ts = new ArrayList<>();
        for(Object obj : fromList){
            T t = copyProp(obj, toC, filterProp);
            ts.add(t);
        }
        return ts;
    }

    public static <T> T copyProp(Object from, Class<T> toC, String... filterProp)  {
        try {
            T t = toC.getConstructor().newInstance();
            copyProp(from, t, filterProp);
            return t;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("BeanUtil.copyProp.exception => " + e.getMessage());
        }
    }

    /**
     * 通过反射复制两个对象的属性
     * @param from 源对象
     * @param to 目录对象
     * @param filterProp
     */
    public static void copyProp(Object from, Object to, String... filterProp)  {
        HashSet<String> filterSet = new HashSet<>(Arrays.asList(filterProp));
        Class<?> fc = from.getClass();
        HashMap<String,Field> fromFieldMap = new HashMap<>();
        Field[] fromFields = fc.getDeclaredFields();
        for(Field field : fromFields){
            fromFieldMap.put(StringTools.lineToHump(field.getName()), field);
        }
        Class<?> tc = to.getClass();
        List<Field> toFieldList = new ArrayList<>() ;
        while (tc != null) {
            toFieldList.addAll(Arrays.asList(tc.getDeclaredFields()));
            tc = tc.getSuperclass();
            if(tc.getClassLoader()==null)break;//说明是非自定义类
        }
        for (Field toField : toFieldList) {
            try{
                String name = StringTools.lineToHump(toField.getName());
                if (!fromFieldMap.containsKey(name) || filterSet.contains(name)) continue;
                Field fromField = fromFieldMap.get(name);
                fromField.setAccessible(true);
                Object value = fromField.get(from);
                if(value==null)continue;
                toField.setAccessible(true);
                Class type = toField.getType();
                if(type==List.class){
                    ParameterizedType listGenericType = (ParameterizedType) fromField.getGenericType();
                    Class<?> listGenericClass = (Class<?>)listGenericType.getActualTypeArguments()[0];
                    if(listGenericClass.getClassLoader()!=null && type!= Time.class){
                        List toList = new ArrayList();
                        List fromList = (List) value;
                        if(fromList.isEmpty()) continue;
                        for(Object fromObj : fromList){
                            Object obj = copyProp(fromObj, listGenericClass);
                            toList.add(obj);
                        }
                        toField.set(to, toList);
                    }else {
                        toField.set(to, value);
                    }
                } else if(type.getClassLoader()!=null && type!= Time.class){
                    Object obj = copyProp(value, type);
                    toField.set(to, obj);
                }else {
                    toField.set(to, value);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过fast json实现一个对象List生成一个新的List
     * @param originList 源List
     * @param tClass 目录List泛型类
     * @return 新的List
     */
    public static <T> List<T> list2list(List originList, Class<T> tClass){
       return JSONArray.parseArray(JSON.toJSONString(originList), tClass);
    }

    /**
     * 通过fast json实现一个对象生成一个新的对象
     * @param bean 源对象
     * @param tClass 目录对象class
     * @return 新对象
     */
    public static <T> T bean2bean(Object bean, Class<T> tClass){
        return JSON.parseObject(JSON.toJSONString(bean),tClass);
    }

    public static <T> List<List<T>> splitList(List<T> in, int size){
        List<List<T>> out = new ArrayList<>();
        int mode = in.size()%size;
        int page = in.size()/size;
        for(int i=1;i<=page;i ++){
            int start = (i-1)*size;
            List<T> sub = in.subList(start,start+size);
            out.add(sub);
        }
        if(mode>0){
            int start = page*size;
            List<T> sub = in.subList(start,start+mode);
            out.add(sub);
        }
        return out;
    }

    /**
     * 集合转树结构
     * @param data 源数据
     * @param rc 返回数据类型CLASS
     * @param idKey id名称
     * @param pidKey 父ID
     * @param childrenKey 孩子key
     * @param pv 父结点值
     * @return 对结构集合
     * @throws Exception
     */
    public static <R> List<R> convertTree(List<R> data, Class<R> rc, String idKey, String pidKey, String childrenKey, Object pv) {
        return convertTree(data,rc,idKey,pidKey,childrenKey,pv, 5);
    }

    public static <R> List<R> convertTree(List<R> data, Class<R> rc, String idKey, String pidKey, String childrenKey, Object pv, int levelLimit) {
        try {
            List<R> treeList = data.stream().filter(x -> {
                try {
                    Field field = rc.getDeclaredField(pidKey);
                    field.setAccessible(true);
                    Object value = field.get(x);
                    if((value+"").equals(pv+""))return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }).collect(Collectors.toList());
            if(treeList.size() >0 ){
                levelLimit --;
                if(levelLimit < 0){
                    throw new RuntimeException("集合转树结构方法超过层级限制");
                }
                for(R treeR : treeList){
                    Field field = rc.getDeclaredField(idKey);
                    field.setAccessible(true);
                    Object value = field.get(treeR);
                    List<R> children = convertTree(data,rc,idKey,pidKey,childrenKey,value, levelLimit);
                    if(!children.isEmpty()){
                        field = rc.getDeclaredField(childrenKey);
                        field.setAccessible(true);
                        field.set(treeR,children);
                    }
                }
            }
            return treeList;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("集合转树结构方法异常");
        }
    }

    public static String urlEncode(String str){
        try {
            return URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

}
posted @ 2020-12-05 10:21  码农记事本  阅读(89)  评论(0)    收藏  举报