BeanUtils { public static Map<String, String> beanMap(Object bean, boolean sorted) { Map<String, String> map = sorted ? new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) : new HashMap<String, String>(); for (Method method : bean.getClass().getMethods()) { if (method.getName().startsWith("get") && !method.getName().equals("getClass") && (method.getReturnType() != null)) { try { Object o = method.invoke(bean); String name = method.getName().substring(3); name = name.substring(0, 1).toLowerCase() + name.substring(1); map.put(name, o == null ? "null" : o.toString()); } catch (Exception e) { } } } return map; } private  BeanUtils(); static Map<String, String> beanMap(Object bean, boolean sorted);  }
@Test public void testToMap() { Map<String, String> map = BeanUtils.beanMap(new MyBean(), false); Assert.assertEquals("foo", map.get("foo")); Assert.assertEquals("3", map.get("bar")); Assert.assertNull(map.get("withParams")); Assert.assertEquals("[<MyBean>, <MyBean>]", map.get("list")); }
@Test public void testToMap_Sorted() { Map<String, String> map = BeanUtils.beanMap(new MyBean(), true); Assert.assertEquals(Arrays.asList("bar", "foo", "list"), new ArrayList<String>(map.keySet())); }