1

这个想法是有一个 POJO 像:

class MyBean {
  long id;
  int count;
  public void setCount(int count){
   this.count = count;
  }
}

现在,我需要将计数自动存储为:

put("count", count);

或者简单地说,put("fieldname", fieldvalue);

是否有可以用于此目的的库MyBean可以扩展?我可以轻松地做一个复制构造函数或其他东西,但是,这里的重点是自动化,而且我的应用程序中有很多模型将让这个 Map 存储 POJO 值......

4

1 回答 1

0

您可以使用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);
于 2013-06-24T09:45:11.707 回答