简体   繁体   English

将POJO转换为适用于GWT的地图

[英]Convert POJO to Map that works with GWT

The idea is to have a POJO like: 这个想法是让POJO像这样:

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

Now, I need that the count be stored automatically as: 现在,我需要将计数自动存储为:

put("count", count);

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

Is there a library that can be used for this purpose that MyBean can exetnd to? 是否存在MyBean可以用于此目的的库? I can easily do a copy constructor or something, however, the point here is automation and besides there are so many models in my app that will be having this Map stored POJO values... 我可以轻松地执行复制构造函数之类的操作,但是,这里的重点是自动化,此外,我的应用程序中还有很多模型将使用此Map存储POJO值...

You could create a simple PropertyMapGenerator using Apache Commons BeanUtils' PropertyUtils 您可以使用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;
    }
}

Now you can simply pass your POJOs to this generator: 现在,您只需将POJO传递给此生成器:

Map<String, Object> propertyMap = PropertyMapGenerator.getPropertyMap(myBean);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM