java map转对象工具类

不念不忘少年蓝@ 2024-03-23 14:55 102阅读 0赞
  1. /**
  2. * @Class BeanUtils
  3. * @Author: zhaoc
  4. * @Version 1.0
  5. * @Date: 2019-07-22
  6. * @Description 类说明
  7. **/
  8. public class BeanUtils {
  9. /****
  10. * Map转Java对象
  11. * @param paramMap
  12. * @param clazz
  13. * @return
  14. * @throws Exception
  15. */
  16. public static Object copyMapToObject(Map<String, Object> paramMap, Class clazz) throws Exception {
  17. Object object = clazz.newInstance();
  18. Field[] fields = clazz.getDeclaredFields();
  19. if(fields != null && fields.length > 0) {
  20. for(Field field : fields) {
  21. String fieldName = field.getName();
  22. String mapVal = StringHandler.getRequestStr(paramMap.get(fieldName));
  23. if(mapVal != null) {
  24. Object paramVal = null;
  25. String fieldType = field.getType().getSimpleName();
  26. if("Long".equals(fieldType)) {
  27. paramVal = Long.valueOf(mapVal);
  28. } else if("Integer".equals(fieldType)) {
  29. paramVal = Integer.parseInt(mapVal);
  30. } else if("BigDecimal".equals(fieldType)) {
  31. paramVal = new BigDecimal(mapVal);
  32. } else if("Date".equals(fieldType)) {
  33. paramVal = DateUtils.parseDate(mapVal);
  34. } else {
  35. paramVal = mapVal;
  36. }
  37. ClassInvokeUtil.setFieldValue(object, fieldName, paramVal);
  38. }
  39. }
  40. }
  41. return object;
  42. }
  43. }
  44. /**
  45. * @Class ClassInvokeUtil
  46. * @Author: zhaoc
  47. * @Version 1.0
  48. * @Date: 2019-07-22
  49. * @Description 类说明
  50. **/
  51. public class ClassInvokeUtil {
  52. public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
  53. String methodName = "set" + upperFirst(fieldName);
  54. Method method = getTargetMethod(obj, methodName);
  55. Object[] paramObj = {value};
  56. method.invoke(obj, paramObj);
  57. }
  58. private static Method getTargetMethod(Object object, String methodName) {
  59. Class clazz = object.getClass();
  60. Method[] methods = clazz.getMethods();
  61. for (int i = 0; i < methods.length; i++) {
  62. if (methodName.equals(methods[i].getName())) {
  63. return methods[i];
  64. }
  65. }
  66. throw new RuntimeException("Invalid target method " + methodName
  67. + " In Class " + object);
  68. }
  69. private static String upperFirst(String name) {
  70. return name.substring(0,1).toUpperCase() +
  71. name.substring(1, name.length());
  72. }
  73. }

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读