public Map<String, String> dtoToMap(EppCommonDto dto) throws ClassNotFoundException { Class clazz = Class.forName(dto.getClass().getName()); // Get all properties of the entity class Field[] fields = clazz.getFields(); Map<String, String> map = new HashMap<>(); // Traverse dto, get attribute values one by one, splicing parameters for (Field fl : fields) { Object value = invokeGetMethod(dto, fl.getName()); if (null == value) { map.put(fl.getName(), ""); } else { map.put(fl.getName(), value.toString()); } } return map; }
private Object invokeGetMethod(Object clazz, String fieldName) { String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method method = null; try { method = Class.forName(clazz.getClass().getName()).getMethod("get" + methodName); return method.invoke(clazz); } catch (Exception e) { LOGGER.error("invokeGetMethod class mapping failed",e); return ""; } }
Only the fields in the conditional dto will be put into the map.