您可以使用Commons BeanUtils http://commons.apache.org/beanutils/ BeanMap http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanMap.html为了这。
Map map = new BeanMap(someBean);
Update:由于 Android 中存在一些明显的库依赖问题,这不是一个选项,这里有一个基本的启动示例,您可以在很少的帮助下完成它反射API http://docs.oracle.com/javase/tutorial/reflect/:
public static Map<String, Object> mapProperties(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<>();
for (Method method : bean.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& method.getName().matches("^(get|is).+")
) {
String name = method.getName().replaceAll("^(get|is)", "");
name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");
Object value = method.invoke(bean);
properties.put(name, value);
}
}
return properties;
}
If java.beans http://docs.oracle.com/javase/6/docs/api/java/beans/package-summary.htmlAPI 可用,那么你可以这样做:
public static Map<String, Object> mapProperties(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<>();
for (PropertyDescriptor property : Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()) {
String name = property.getName();
Object value = property.getReadMethod().invoke(bean);
properties.put(name, value);
}
return properties;
}