java使用反射调用对象get方法

时间:2025-03-10 18:43:55
private static volatile SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); /** * 反射获取get值 * * @param obj * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static HashMap<String, String> invokeGetMethod(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // 获取对象class Class<?> aClass = obj.getClass(); // 获取对象声明字段 Field[] declaredFields = aClass.getDeclaredFields(); HashMap<String, String> result = new HashMap<>(127); for (Field declaredField : declaredFields) { String fieldName = declaredField.getName(); if("serialVersionUID".equals(fieldName)){ continue; } // 拼接方法名 String firstCharUpper = fieldName.substring(0, 1).toUpperCase(); String invokeMethodName = "get" + firstCharUpper + fieldName.substring(1); // 获取方法 Method pendingInvokeMethod = aClass.getMethod(invokeMethodName); // 执行方法 Object invokeResult = pendingInvokeMethod.invoke(obj); // 下可省略 if (ObjectUtil.isNull(invokeResult) ){ result.put(fieldName, ""); } else if (invokeResult instanceof Date) { String date = format.format((Date) invokeResult); result.put(fieldName, date); } else { result.put(fieldName, invokeResult.toString()); } } return result; }