专栏首页码客实体类的Copy

实体类的Copy

class<-->class class<-->map

该工具类主要实现了实体类与实体类之间的转化以及实体类与map之间的转化

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * 
 * @author 张剑
 * @version 1.2
 * 
 */
public class ZJ_BeanUtils {

    /**
     * java反射bean的get方法
     * 
     * @param objectClass
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Method getGetMethod(Class objectClass, String fieldName) throws NoSuchMethodException, SecurityException {
        Method method = null;
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("get");
            sb.append(fieldName.substring(0, 1).toUpperCase());
            sb.append(fieldName.substring(1));
            method = objectClass.getMethod(sb.toString());
        } catch (Exception e) {
            StringBuffer sb = new StringBuffer();
            sb.append("is");
            sb.append(fieldName.substring(0, 1).toUpperCase());
            sb.append(fieldName.substring(1));
            method = objectClass.getMethod(sb.toString());
        }
        return method;
    }

    /**
     * java反射bean的set方法
     * 
     * @param objectClass
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws NoSuchMethodException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static Method getSetMethod(Class objectClass, String fieldName) throws NoSuchFieldException, SecurityException, NoSuchMethodException {
        Method method = null;
        Class[] parameterTypes = new Class[1];
        Field field = objectClass.getDeclaredField(fieldName);
        parameterTypes[0] = field.getType();
        StringBuffer sb = new StringBuffer();
        sb.append("set");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        method = objectClass.getMethod(sb.toString(), parameterTypes);
        return method;
    }

    /**
     * 执行set方法
     * 
     * @param o
     *            执行对象
     * @param fieldName
     *            属性
     * @param value
     *            值
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws NoSuchFieldException
     */
    private static void invokeSet(Object o, String fieldName, Object value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, SecurityException, NoSuchMethodException {
        Method method = getSetMethod(o.getClass(), fieldName);
        method.invoke(o, new Object[] { value });
    }

    /**
     * 执行get方法
     * 
     * @param o
     *            执行对象
     * @param fieldName
     *            属性
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SecurityException
     * @throws NoSuchMethodException
     */
    private static Object invokeGet(Object o, String fieldName) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        Method method = getGetMethod(o.getClass(), fieldName);
        return method.invoke(o, new Object[0]);
    }

    /**
     * 是否有字段
     * 
     * @param o
     * @param fieldName
     * @return
     */
    private static boolean isHasField(Object o, String fieldName) {
        Object[] objects = getFieldNamesByMethod(o);
        for (Object object : objects) {
            if (object.toString().equals(fieldName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 数组中是否包含字符串
     * 
     * @param ignoreProperties
     * @param str
     * @return
     */
    private static boolean isHasStr(String[] ignoreProperties, String str) {
        for (String string : ignoreProperties) {
            if (string.equals(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取对象所有字段(通过方法)
     * 
     * @param obj
     * @return
     */
    public static Object[] getFieldNamesByMethod(Object obj) {
        Set set = new TreeSet();
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get")) {
                name = name.substring(3);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                set.add(name);
            } else if (name.startsWith("is")) {
                name = name.substring(2);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                set.add(name);
            }
        }
        if (set.contains("class")) {
            set.remove("class");
        }
        Object[] fieldStrs = set.toArray();
        return fieldStrs;
    }

    /**
     * 获取对象所有字段(通过属性)
     * 
     * @param obj
     * @return
     */
    public static Object[] getFieldNamesByField(Object obj) {
        Set set = new TreeSet();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (null != name && !"".equals(name)) {
                set.add(name);
            }
        }
        if (set.contains("class")) {
            set.remove("class");
        }
        Object[] fieldStrs = set.toArray();
        return fieldStrs;
    }

    /**
     * 获取对象所有字段(通过属性和方法)
     * 
     * @param obj
     * @return
     */
    public static Object[] getFieldNamesByAll(Object obj) {
        Set set = new TreeSet();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (null != name && !"".equals(name)) {
                set.add(name);
            }
        }
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get")) {
                name = name.substring(3);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                set.add(name);
            } else if (name.startsWith("is")) {
                name = name.substring(2);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                set.add(name);
            }
        }
        if (set.contains("class")) {
            set.remove("class");
        }
        Object[] fieldStrs = set.toArray();
        return fieldStrs;
    }

    /**
     * 获取对象所有字段名称与类型(通过方法)
     * 
     * @param obj
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map getFieldMsgByMethod(Object obj) {
        Map map = new TreeMap();
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get")) {
                name = name.substring(3);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                map.put(name, method.getReturnType().getName());
            } else if (name.startsWith("is")) {
                name = name.substring(2);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                map.put(name, method.getReturnType().getName());
            }
        }
        if (map.keySet().contains("class")) {
            map.remove("class");
        }
        return map;
    }

    /**
     * 获取对象所有字段名称与类型(通过属性)
     * 
     * @param obj
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map getFieldMsgByField(Object obj) {
        Map map = new TreeMap();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (null != name && !"".equals(name)) {
                map.put(name, field.getType().getName());
            }
        }
        if (map.keySet().contains("class")) {
            map.remove("class");
        }
        return map;
    }

    /**
     * 获取对象所有字段名称与类型(通过属性和方法)
     * 
     * @param obj
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map getFieldMsgByAll(Object obj) {
        Map map = new TreeMap();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (null != name && !"".equals(name)) {
                map.put(name, field.getType().getName());
            }
        }
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get")) {
                name = name.substring(3);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                map.put(name, method.getReturnType().getName());
            } else if (name.startsWith("is")) {
                name = name.substring(2);
                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                map.put(name, method.getReturnType().getName());
            }
        }
        if (map.keySet().contains("class")) {
            map.remove("class");
        }
        return map;
    }

    /**
     * copy(class-->class)
     * 
     * @param source源
     * @param target目标
     * @param isCopyNull是否拷贝null
     * @param ignoreProperties忽略的字段
     * @return
     */
    public static void copyProperties(Object source, Object target, boolean isCopyNull, String[] ignoreProperties) {
        Object[] fields = getFieldNamesByMethod(source);
        for (Object field : fields) {
            String name = field.toString();
            Object value = null;
            try {
                value = invokeGet(source, name);
                if (null != ignoreProperties && isHasStr(ignoreProperties, name)) {
                    continue;
                }
                if (isHasField(target, name)) {
                    if (null != value) {
                        invokeSet(target, name, value);
                    } else if (isCopyNull) {
                        invokeSet(target, name, value);
                    }
                }
            } catch (Exception e) {
                continue;
            }
        }
    }

    /**
     * copy(class-->class)
     * 
     * @param source源
     * @param target目标
     * @param isCopyNull是否拷贝null
     * @return
     */
    public static void copyProperties(Object source, Object target, boolean isCopyNull) {
        copyProperties(source, target, isCopyNull, null);
    }

    /**
     * copy(map-->class)
     * 
     * @param map源
     * @param target目标
     * @param isCopyNull是否拷贝null
     * @param ignoreProperties忽略的字段
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static void copyProperties(Map map, Object target, boolean isCopyNull, String[] ignoreProperties) {
        Set set = map.keySet();
        for (Object object : set) {
            try {
                String name = object.toString();
                Object value = map.get(name);
                if (null != ignoreProperties && isHasStr(ignoreProperties, name)) {
                    continue;
                }
                if (isHasField(target, name)) {
                    if (null != value) {
                        invokeSet(target, name, value);
                    } else if (isCopyNull) {
                        invokeSet(target, name, value);
                    }
                }
            } catch (Exception e) {
                continue;
            }
        }
    }

    /**
     * copy(map-->class)
     * 
     * @param map源
     * @param target目标
     * @param isCopyNull是否拷贝null
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static void copyProperties(Map map, Object target, boolean isCopyNull) {
        copyProperties(map, target, isCopyNull, null);
    }

    /**
     * copy(class-->map)
     * 
     * @param source源
     * @param map目标
     * @param isCopyNull是否拷贝null
     * @param ignoreProperties忽略的字段
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void copyProperties(Object source, Map map, boolean isCopyNull, String[] ignoreProperties) {
        Object[] fieldNames = getFieldNamesByMethod(source);
        for (Object field : fieldNames) {
            String name = field.toString();
            Object value = null;
            try {
                value = invokeGet(source, name);
                if (null != ignoreProperties && isHasStr(ignoreProperties, name)) {
                    continue;
                }
                if (null != value) {
                    map.put(name, value);
                } else if (isCopyNull) {
                    map.put(name, value);
                }
            } catch (Exception e) {
                System.out.println(e);
                continue;
            }
        }
    }

    /**
     * copy(class-->map)
     * 
     * @param source源
     * @param map目标
     * @param isCopyNull是否拷贝null
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static void copyProperties(Object source, Map map, boolean isCopyNull) {
        copyProperties(source, map, isCopyNull, null);
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Flutter开发-网络请求与JSON转换

    如果发送的数据是FormData,则dio会将请求header的contentType设为“multipart/form-data”。

    剑行者
  • Flutter开发-网络请求与JSON转换

    如果发送的数据是FormData,则dio会将请求header的contentType设为“multipart/form-data”。

    剑行者
  • 网站头配置

    我们只需在网站的head标签中添加上面的代码,即可以相对应的模式来渲染网站。 同时我们也可以同时指定多个内核名称,之间以符号”|”进行分隔,如下代码:

    剑行者
  • xcode编译的时候陷入无限indexing的问题笔记

    “Swift因为有类型推断,一般来说你很少需要写类型标注。如果你在声明常量或者变量的时候赋了一个初始值,Swift可以推断出这个常量或者变量的类型”,而事实上,...

    练小习
  • Crowd 批量添加用户(Postman 数据驱动)

    最近公司大量新员工入职,需要批量创建 Crowd 用户、设置密码、分配应用组等机械性重复工作(主要还是懒~),故把这个加餐任务分配给刚来的测试同学去研究。

    叨叨软件测试
  • pyRedis - 操作指南:增/删/改/查、管道与发布订阅功能

    首先拉取 Redis 镜像, 这里我选择的是 redis:alpine 轻量级镜像版本:

    素质
  • [python]父类、子类、子类实例属性

    py3study
  • Memcached·Redis缓存的基本操作

    Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、...

    Wyc
  • python操作数据库

    pip install redispy 参考:https://www.cnblogs.com/john-xiong/p/12089103.html

    sofu456
  • Python之Django自动实现html代码(下拉框,数据选择)

    补充知识:django使用模板实现下拉菜单,菜单内容读取后台动态填充,并动态设置默认值

    砸漏

扫码关注云+社区

领取腾讯云代金券