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;
}
java使用反射调用对象get方法
最新推荐文章于 2025-05-16 10:43:13 发布
该博客主要介绍了Java中反射机制的使用,通过反射获取对象的get方法,并将获取到的Date类型字段转换为指定的'yy-MM-dd HH:mm:ss'格式字符串。内容包括反射获取字段、执行方法以及日期格式化处理。
1029

被折叠的 条评论
为什么被折叠?



