對java中以對象方式將對象的參數將其各屬性值中的空格去除

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TrimUtil {

    /**
     * 將對象中的參數進行去空格
     * 
     * @param obj
     * @return
     */
    public static Object trimObject(Object obj) {
        if (obj == null)
            return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            Class<?> type = field.getType();
            if ("class java.lang.String".equals(type.toString())) {
                String fieldName = field.getName();
                Object value = getValueByFieldName(fieldName, obj);
                if (value != null) {
                    doSetValue(obj, type, fieldName, value.toString().trim());//去除前後端空格  
                    //doSetValue(obj, type, fieldName, value.toString().replace(" ", ""));//去除所有空格
                }
            }

        }
        return obj;

    }

    /** 
     * 根據屬性名獲取該類此屬性的值 
     * @param fieldName 
     * @param object 
     * @return 
     */
    private static Object getValueByFieldName(String fieldName, Object object) {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        try {
            Method method = object.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(object, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 將處理過的值放入對象中
     * 
     * @param obj
     * @param classType
     * @param fieldName
     * @param value
     */
    private static void doSetValue(Object obj, Class<?> classType, String fieldName, String value) {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String setter = "set" + firstLetter + fieldName.substring(1);
        try {
            Method method = obj.getClass().getMethod(setter, new Class[] { classType });
            method.invoke(obj, new Object[] { value });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章