问题描述
我有一个POJO,和(目前还未建)类,将返回它的列表。我想自动生成必要的POJO进行访问,地图上的code。这是一个好主意,是有可能自动做的,我需要手动为每一个POJO我想治疗这种方式做到这一点?
I have a POJO, and a (currently not-yet-built) class that will return Lists of it. I'd like to automatically generate the code necessary for the POJO to be accessed as a Map. Is this a good idea, is it possible to do automatically, and do I need to do this manually for every POJO I want to treat this way?
谢谢,刘德华
推荐答案
您可以使用共享的beanutils <$c$c>BeanMap$c$c>对于这一点。
You can use Commons BeanUtils BeanMap
for this.
Map map = new BeanMap(someBean);
更新:因为这不是一种选择,由于Android的一些明显的库相关问题,这里有一个基本的开球例如你怎么可以用的:
Update: since that's not an option due to some apparent library dependency problems in Android, here's a basic kickoff example how you could do it with little help of Reflection API:
public static Map<String, Object> mapProperties(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
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;
}
我不知道,如果<$c$c>java.beans$c$c> API是在Android中使用,但如果是真的,那么你可以取代
I am not sure if java.beans
API is available in Android, but if true, then you could replace
name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");
按
name = Introspector.decapitalize(name);
这篇关于生成地图&LT;字符串,字符串&GT;从POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!