提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
从Java Bean对象获取字段值映射
/* 时 代 J a v a 公 众 号 - nowjava.com 提供 */ //package com.nowjava; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class Main { public static void main(String[] argv) throws Exception { Object bean = "nowjava.com"; /* *来 自 NowJava.com - 时代Java */ System.out.println(getFieldValueMap(bean)); } public static Map<String, String> getFieldValueMap(Object bean) { Class<?> cls = bean.getClass(); Map<String, String> valueMap = new HashMap<String, String>(); // ????bean?????? Method[] methods = cls.getDeclaredMethods(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { try { String fieldType = field.getType().getSimpleName(); String fieldGetName = parGetName(field.getName()); if (!checkGetMet(methods, fieldGetName)) { continue; } Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {}); Object fieldVal = fieldGetMet.invoke(bean, new Object[] {}); String result = null; if ("Date".equals(fieldType)) { result = fmtDate((Date) fieldVal); } else { if (null != fieldVal) { result = String.valueOf(fieldVal); } } if (result != null && !"".equals(result) && !"page".equals(field.getName()) && !"rows".equals(field.getName())) { valueMap.put(field.getName(), result); } } catch (Exception e) { continue; } } return valueMap; } public static String parGetName(String fieldName) { if (null == fieldName || "".equals(fieldName)) { return null; } return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } public static boolean checkGetMet(Method[] methods, String fieldGetMet) { for (Method met : methods) { if (fieldGetMet.equals(met.getName())) { return true;