标签:
【转换字段名为get/set方法名】
/** * 给Object对象设置某属性值 * @param obj Object * @param columnName String * @param value Object * @return */ public Boolean setPropertyByColumn(Object obj,String columnName,Object value) { try { if (obj!=null && columnName!=null) { java.lang.reflect.Method set = obj.getClass().getDeclaredMethod( transColumn2GetOrSetMethodName(columnName,"set"), value.getClass()); set.invoke(obj, value); return true; } else { return false; } } catch (Exception e) { return false; } } /** * 根据列名获取对应的get或set方法名 * @param column String * @param setOrget String * @return */ public String transColumn2GetOrSetMethodName(String column,String setOrget){ if (column==null || setOrget==null) { return null; } if (setOrget.matches("set|get")) { String[] colps = column.toLowerCase().split("_"); String methodName = "set"; for (int i = 0; i < colps.length; i++) { if (colps[i].length() > 1) { methodName += new String(colps[i].substring(0, 1).toUpperCase()); methodName += new String(colps[i].substring(1)); } else { methodName += new String(colps[i].toUpperCase()); } } return methodName; } else { System.out.println("param setOrget must be set or get.");
return null; } } /** * 获取Object某属性值 * @param obj Object * @param columnName String * @return */ public Object getPropertyByColumn(Object obj,String columnName) { try { if (obj!=null && columnName!=null) { java.lang.reflect.Method get = obj.getClass().getDeclaredMethod( transColumn2GetOrSetMethodName(columnName,"get")); return get.invoke(obj); } else { return null; } } catch (Exception e) { return null; } }
标签:
原文地址:http://www.cnblogs.com/justbeginning/p/4261913.html