利用發射進行對象賦值

/**
 * 兩個相同屬性的對象賦值
 *
 * @param sourceObj
 * @param targetObj
 */

public static void entityPropertiesCopy(Object sourceObj, Object targetObj) {
    if (sourceObj == null || targetObj == null)
        return;

    Class targetClass = null;
    //用java反射機制就能夠, 能夠作成通用的方法, 只要屬性名和類型同樣
    Field[] sourceFields = null;
    try {
        targetClass = targetObj.getClass();
        sourceFields = sourceObj.getClass().getDeclaredFields();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String fieldName = "";
    Class fieldType = null;

    for (int i = 0; i < sourceFields.length; i++) {
        try {
            fieldName = sourceFields[i].getName();
            fieldType = sourceFields[i].getType();
            Field targetField = targetClass.getDeclaredField(fieldName);
            if (targetField != null && targetField.getType().equals(fieldType)) {
                Method sourceGetter = sourceObj.getClass().getMethod(getGetMethodName(fieldName));
                Method targetSetter = targetObj.getClass().getMethod(getSetMethodName(fieldName), new Class<?>[]{fieldType});
                Object fieldValue = sourceGetter.invoke(sourceObj);
                if (fieldValue != null) {
                    targetSetter.invoke(targetObj, new Object[]{fieldValue});
                }
            }
        } catch (NoSuchFieldException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public static String getGetMethodName(String fieldName) {
    String result = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    return "get" + result;
}

public static String getSetMethodName(String fieldName) {
    String result = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    return "set" + result;

}
相關文章
相關標籤/搜索