使用反射,可以对实体类中的所有String类型的成员变量的值执行trim操作
(1)trim
/*** * 对object中的所有成员变量的值,执行trim操作 * 即去掉首尾的空格 * @param obj * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void trimObject(Object obj) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if(obj==null){ return; } ListfieldsList =getAllFieldList(obj.getClass()); for(int i=0;i
应用场景
// 是否清除成员变量的值前后的空格 boolean isTrim2=false; String isTrim22Str=DictionaryParam.get(Constant2.DICTIONARY_GROUP_GLOBAL_SETTING,"is_trim_columnValue"); if(!ValueWidget.isNullOrEmpty(isTrim22Str)){ isTrim2=Boolean.parseBoolean(isTrim22Str); } if(isTrim2&&user!=null){ try { ReflectHWUtils.trimObject(user); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
(2)把值为空字符串的成员变量设置为null
/*** * 把对象中空字符串改为null * @param obj : 要修改的对象:java bean * @param isTrim : 是否清除成员变量的值前后的空格 * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void convertEmpty2Null(Object obj,boolean isTrim) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ if(obj==null){ return; } ListfieldsList =getAllFieldList(obj.getClass()); for(int i=0;i
应用场景:
// 是否清除成员变量的值前后的空格 boolean isTrim2=false; String isTrim22Str=DictionaryParam.get(Constant2.DICTIONARY_GROUP_GLOBAL_SETTING,"is_trim_columnValue"); if(!ValueWidget.isNullOrEmpty(isTrim22Str)){ isTrim2=Boolean.parseBoolean(isTrim22Str); } try { //把对象中空字符串改为null ReflectHWUtils.convertEmpty2Null(ordersDetail,isTrim2); if(!ValueWidget.isNullOrEmpty(ordersDetail.getToothOrders())){ ReflectHWUtils.convertEmpty2Null(ordersDetail.getToothOrders(),isTrim2);//不需要再set一遍 } if(!ValueWidget.isNullOrEmpty(ordersDetail.getProducts())){ ReflectHWUtils.convertEmpty2Null(ordersDetail.getProducts(),isTrim2);//不需要再set一遍 } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }