集册 Java实例教程 复制(地图

复制(地图

欢马劈雪     最近更新时间:2020-01-02 10:19:05

419
复制(map-> class)


//package com.nowjava;
/**
来 自 n o w j a v a . c o m - 时  代  Java
**/

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Map;

import java.util.Set;


public class Main {


    @SuppressWarnings("rawtypes")

    public static void copyPropertiesMapArray(Map<String, String[]> map,

            Object target, boolean isCopyNull, String[] ignoreProperties) {

        Set set = map.keySet();

        for (Object object : set) {

            try {

                String name = object.toString();

                String value = map.get(name)[0];

                if (null != ignoreProperties// 来自 N o  w  J a v a . c o m - 时  代  Java

                        && 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;

            }

        }

    }


    public static void copyPropertiesMapArray(Map<String, String[]> map,

            Object target, boolean isCopyNull) {

        copyPropertiesMapArray(map, target, isCopyNull, null);

    }


    private static boolean isHasStr(String[] ignoreProperties, String str) {

        for (String string : ignoreProperties) {

            if (string.equals(str)) {

                return true;

            }

        }

        return false;

    }


    private static boolean isHasField(Object o, String fieldName) {

        Field[] fields = getFields(o);

        for (Field field : fields) {

            if (field.getName().equals(fieldName)) {

                return true;

            }

        }

        return false;

    }


    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 });

    }


    private static Field[] getFields(Object o) {

        Field[] fields = o.getClass().getDeclaredFields();

        return fields;

    }


    @SuppressWarnings({ "rawtypes", "unchecked" })

    private static Method getSetMethod(Class objectClass, String fiel
展开阅读全文