Map -> Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

Map -> Bean

Demo Code


import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class Main{
    private static String FIELD_DATE_FORMAT = "yyyy-MM-dd";
    private static String[] FIELD_TYPE_SIMPLE = { "java.lang.String",
            "java.lang.Integer", "int", "java.util.Date",
            "java.math.BigDecimal" };
    private static String FIELD_TYPE_INTEGER = "java.lang.Integer,int";
    private static String FIELD_TYPE_DATE = "java.util.Date";
    private static String FIELD_TYPE_BIGDECIMAL = "java.math.BigDecimal";
    public static void copyProperties(Map srcMap, Object targetObj)
            throws Exception {
        copyProperties(srcMap, targetObj, false);
    }// ww w  .  j a  v a2  s.c  o  m
    
    public static void copyProperties(Map srcMap, Object targetBean,
            boolean isToCamel) {
        try {
            PropertyDescriptor[] propertyDescriptors = Introspector
                    .getBeanInfo(targetBean.getClass())
                    .getPropertyDescriptors();
            for (PropertyDescriptor prop : propertyDescriptors) {
                Method writeMethod = prop.getWriteMethod();
                if (writeMethod != null) {
                    for (Object obj : srcMap.keySet()) {
                        String mapKey = (String) obj;
                        String mapkeyCamel = isToCamel ? toCamel(mapKey
                                .toLowerCase()) : mapKey;
                        String beanPropName = isToCamel ? toCamel(prop
                                .getName()) : prop.getName();
                        if (mapkeyCamel.equals(beanPropName)) {
                            if (!Modifier.isPublic(writeMethod
                                    .getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            Object value = srcMap.get(mapKey);
                            if (value == null) {
                                break;
                            }
                            if (!(prop.getPropertyType().getName()
                                    .equals(value.getClass().getName()))) {
                                value = parseByType(prop.getPropertyType(),
                                        value.toString());
                            }
                            writeMethod.invoke((Object) targetBean,
                                    new Object[] { value });
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Map->Bean copy .", e);
        }
    }
    public static void copyProperties(Object source, Object target) {
        copyProperties(source, target, false);
    }
    
    public static void copyProperties(Object source, Object target,
            boolean isToCamel) {
        try {
            PropertyDescriptor[] targetProps = Introspector.getBeanInfo(
                    target.getClass()).getPropertyDescriptors();
            for (PropertyDescriptor targetProp : targetProps) {
                Method writeMethod = targetProp.getWriteMethod();
                if (writeMethod != null) {
                    PropertyDescriptor[] srcProps = Introspector
                            .getBeanInfo(source.getClass())
                            .getPropertyDescriptors();
                    for (PropertyDescriptor srcProp : srcProps) {
                        String srcPropName = isToCamel ? toCamel(srcProp
                                .getName()) : srcProp.getName();
                        String targetPropName = isToCamel ? toCamel(targetProp
                                .getName()) : targetProp.getName();
                        if (srcPropName.equals(targetPropName)) {
                            Method readMethod = srcProp.getReadMethod();
                            if (!Modifier.isPublic(readMethod
                                    .getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source,
                                    new Object[0]);
                            if (value == null) {
                                break;
                            }
                            if (!Modifier.isPublic(writeMethod
                                    .getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            if (!(targetProp.getPropertyType().getName()
                                    .equals(value.getClass().getName()))) {
                                value = parseByType(
                                        targetProp.getPropertyType(), value);
                            }

                            writeMethod.invoke((Object) target,
                                    new Object[] { value });
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Bean->Bean copy error.", e);
        }
    }
    private static String toCamel(String srcStr) {

        StringBuilder sb = new StringBuilder();
        boolean match = false;
        for (int i = 0; i < srcStr.length(); i++) {
            char ch = srcStr.charAt(i);
            if (match && ch >= 97 && ch <= 122)
                ch -= 32;
            if (ch != '_') {
                match = false;
                sb.append(ch);
            } else {
                match = true;
            }
        }
        return sb.toString();
    }
    private static Object parseByType(Class targetClazz, Object srcObj)
            throws ParseException, InstantiationException,
            IllegalAccessException, SecurityException,
            IllegalArgumentException, NoSuchMethodException,
            InvocationTargetException {
        Object obj = "";
        String clazzName = targetClazz.getName().trim();
        if (isSimpleType(clazzName)) {
            String srcStr = srcObj.toString();
            if (FIELD_TYPE_INTEGER.contains(clazzName)) {
                obj = parseInteger(srcStr);
            } else if (FIELD_TYPE_DATE.contains(clazzName)) {
                obj = parseDate(srcStr);
            } else if (FIELD_TYPE_BIGDECIMAL.contains(clazzName)) {
                obj = parseBigDecimal(srcStr);
            } else {
                obj = srcStr;
            }
        } else {
            obj = srcObj;
        }
        return obj;
    }
    private static boolean isSimpleType(String type) {
        for (int i = 0; i < FIELD_TYPE_SIMPLE.length; i++) {
            if (type.equals(FIELD_TYPE_SIMPLE[i])) {
                return true;
            }
        }
        return false;
    }
    private static Integer parseInteger(String str) {
        if (str == null || str.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(str);
        }
    }
    private static Date parseDate(String str) throws ParseException {
        if (str == null || str.equals("")) {
            return null;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat(FIELD_DATE_FORMAT);
            Date date = sdf.parse(str);
            return date;
        }
    }
    private static BigDecimal parseBigDecimal(String str)
            throws ParseException {
        if (str == null || str.equals("")) {
            return null;
        } else {
            return new BigDecimal(str);
        }
    }
}

Related Tutorials