这个想法是有一个像这样的 POJO:
class MyBean {
long id;
int count;
public void setCount(int count){
this.count = count;
}
}
现在,我需要将计数自动存储为:
put("count", count);
或者简单地说,put("fieldname", fieldvalue);
是否有一个库可以用于此目的,MyBean
可以 exetnd 到?我可以轻松地执行复制构造函数或其他操作,但是,这里的重点是自动化,此外我的应用程序中有很多模型将让这个 Map 存储 POJO 值...
最佳答案
您可以使用 Apache Commons BeanUtils' PropertyUtils 创建一个简单的 PropertyMapGenerator
public class PropertyMapGenerator {
public static Map<String, Object> getPropertyMap(Object object) {
HashMap<String, Object> propertyMap = new HashMap<>();
// retrieve descriptors for all properties
PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object);
for (PropertyDescriptor descriptor : descriptors) {
// check if there is a reader method for this property i.e. if it can be accessed
if (descriptor.getReadMethod() != null) {
String name = descriptor.getName();
try {
propertyMap.put(name, PropertyUtils.getProperty(object, name));
} catch (Exception e) {
// handle this properly
e.printStackTrace();
}
}
}
return propertyMap;
}
}
现在您可以简单地将 POJO 传递给此生成器:
Map<String, Object> propertyMap = PropertyMapGenerator.getPropertyMap(myBean);
关于java - 将 POJO 转换为可与 GWT 配合使用的 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17271783/