实体类的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);
    }
}