java - 将 POJO 转换为可与 GWT 配合使用的 Map

标签 java gwt

这个想法是有一个像这样的 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/

相关文章:

eclipse - 在 eclipse 中将 GWT 应用程序部署到 tomcat 的问题

java - Web 开发人员还应该学习 JavaScript 吗?

java - 不确定为什么我的实例出现错误

java - 检测弹性表中按下了哪个按钮

java - 在文本框中设置日期?

gwt - 在GWT中动态替换DIV的内部文本

java - JDO 持久字段返回 null

java - 如何在 Spring Boot 中通过 websocket 代理按照提交顺序发送消息?

java - Android 按钮动画

java - 在并行模式下使用 maven-surefire-plugin 时如何识别缓慢的单元测试?