栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

封装个基于java反射处理对象的工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

封装个基于java反射处理对象的工具类

说明

总结了一个基于反射的工具类,目前可以实现的:

  • 将数组下标对应的值赋值给对象
  • 比较两个对象字段是否完全一致,获取不一致的字段名集合
  • 比较两个对象的字段是否完全一致
  • 获取对象的字段与类型键值对
  • 得到对象内除指定字段外的的字段名集合
  • 得到类里带指定注解的字段
  • 将Object转化为List
  • 将多个相同的对象添加到列表当中
  • 交换相同字段的值,返回字段交换的对象
工具类
public class ObjectUtils {


    
    @SneakyThrows
    public static  T initObject(Class clazz, String[] cols) {
        Field[] fields = clazz.getDeclaredFields();
        T instance = clazz.newInstance();
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].getType() == String.class) {
                copyToField(instance, fields[i].getName()).set(instance, cols[i]);
            } else if (fields[i].getType() == Date.class) {
                if (!isEmpty(cols[i]) && isDate(cols[i])) {
                    copyToField(instance, fields[i].getName()).set(instance, getDate(cols[i]));
                } else {
                    copyToField(instance, fields[i].getName()).set(instance, null);
                }
            } else if (fields[i].getType() == Double.class) {
                if (!isEmpty(cols[i])) {
                    copyToField(instance, fields[i].getName()).set(instance, Double.parseDouble(cols[i]));
                } else {
                    copyToField(instance, fields[i].getName()).set(instance, null);
                }
            } else if (fields[i].getType() == Integer.class) {
                if (!isEmpty(cols[i])) {
                    copyToField(instance, fields[i].getName()).set(instance, Integer.parseInt(cols[i]));
                } else {
                    copyToField(instance, fields[i].getName()).set(instance, null);
                }
            } else if (fields[i].getType() == Long.class) {
                if (!isEmpty(cols[i])) {
                    copyToField(instance, fields[i].getName()).set(instance, Long.parseLong(cols[i]));
                } else {
                    copyToField(instance, fields[i].getName()).set(instance, null);
                }
            } else if (fields[i].getType() == Boolean.class) {
                if (!isEmpty(cols[i])) {
                    copyToField(instance, fields[i].getName()).set(instance, Boolean.parseBoolean(cols[i]));
                } else {
                    copyToField(instance, fields[i].getName()).set(instance, null);
                }
            }
        }
        return instance;
    }



    public static List compareDiffFields(Object obj1, Object obj2){
        List fs1 = Arrays.stream(obj1.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        List fs2 = Arrays.stream(obj2.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        List fields = new ArrayList<>();
        if(fs1.size() > fs2.size()){
            for (String f1 : fs1)
                if(!fs2.contains(f1))
                    fields.add(f1);
            return fields.size() > 0 ? fields : Collections.emptyList();
        } else {
            for (String f2 : fs2)
                if(!fs1.contains(f2))
                    fields.add(f2);
            return fields.size() > 0 ? fields : Collections.emptyList();
        }
    }


    
    public static Boolean isFieldsEquals(Object obj1, Object obj2){
        List fs1 = Arrays.stream(obj1.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        List fs2 = Arrays.stream(obj2.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        if(fs1.size() == fs2.size()){
            for (String f1 : fs1)
                if(!fs2.contains(f1))
                    return false;
            return true;
        }
        return false;
    }


    
    public static Map> withFieldsAndTypes(Class clazz) {
        Map> kv = new Hashtable<>();
        for (Field field : clazz.getDeclaredFields()) {
            kv.put(field.getName(), field.getType());
        }
        return kv;
    }


    
    public static List filterFields(Class clazz, String... excludes) {
        List fieldList = new ArrayList<>();
        while (clazz != null) {

            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }

        Field[] fields = fieldList.stream().toArray(Field[]::new);
        List result = new ArrayList<>();

        for (Field field : fields) {
            result.add(field.getName());
        }

        for (String fieldName : excludes) {
            result.remove(fieldName);
        }

        return result;
    }


    
    public static List getAnnotationFields(Class clazz, Class annotatedClass){
        List fields = new ArrayList<>();
        Field[] declaredFields = clazz.getDeclaredFields();
        if (declaredFields.length != 0)
        {
            for (Field field : declaredFields)
            {
                if (field.getAnnotation(annotatedClass) != null)
                {
                    fields.add(field.getName());
                }
            }
            return fields;
        }
        return null;
    }

    
    public static  List castList(Object obj, Class clazz)
    {
        List result = new ArrayList();
        if(obj instanceof List)
        {
            for (Object o : (List) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    
    @SafeVarargs
    public static  List asMergedList(T ...merged){

        return new ArrayList(Arrays.asList(merged));
    }


    
    public static  T tempObject(Object target, T result){
        BeanUtils.copyProperties(target, result);
        return result;
    }


    
    @SneakyThrows
    private static Field copyToField(Object instance, String fieldName){
        Field f = instance.getClass().getDeclaredField(fieldName);
        f.setAccessible(true);
        return f;
    }

    private static Date getDate(String dateStr) throws ParseException {
        if (dateStr.length() > 23) {
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
            return sdf.parse(dateStr);
        } else {
            return dateStr.length() > 8 && dateStr.contains(":") ? getFullDate(dateStr) : getSimpleDate(dateStr);
        }
    }


    private static Date getFullDate(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateStr.contains("T") ? "yyyy-MM-dd'T'HH:mm:ss" : "yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr);
        } catch (ParseException var2) {
            var2.printStackTrace();
            return null;
        }
    }

    private static Date getSimpleDate(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr);
        } catch (ParseException var2) {
            var2.printStackTrace();
            return null;
        }
    }

    private static Boolean isDate(String str) {
        try {
            DateUtils.parseDate(str, "yyyy-MM-dd HH:mm:ss");
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    private static boolean isEmpty(String str) {
        return null != str && str.length() > 0;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959362.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号