【问题标题】:Copy pojo fields to another pojo's setters将 pojo 字段复制到另一个 pojo 的 setter
【发布时间】:2013-12-04 08:54:39
【问题描述】:

假设我的课程 A 带有公共字段 xy。假设我有另一个 pojo 类 B,但它使用 setter 和 getter,所以它有 setX() 和 setY()。

我想使用某种自动方式从A 的实例复制到B 并返回。

至少在默认设置下,Dozer 的

   Mapper mapper = new DozerBeanMapper();
   B b = mapper.map(a, B.class);

没有正确复制字段。

那么是否有一个简单的配置更改允许我使用 Dozer 或其他可以为我完成此操作的库来完成上述操作?

【问题讨论】:

  • 您是否尝试过使用 JAXB、ObjectMapper?还是您只想使用推土机?
  • 不,我没有。在上述情况下,我很乐意使用任何提供“单行转换”的库。
  • 您想使用 jaxb,它执行基于注释的绑定,所以我认为它应该适合您。在同一页面结帐wiki.fasterxml.com/JacksonDocumentation 和教程

标签: java pojo dozer


【解决方案1】:

我建议你使用:

http://modelmapper.org/

或者看看这个问题:

Copy all values from fields in one class to another through reflection

我想说 API (BeanUtils) 和 ModelMapper 都为将 pojos 的值复制到另一个 pojos 提供了单行。看看@这个:

http://modelmapper.org/getting-started/

【讨论】:

  • 好的,ModelMapper 完成了这项工作,但有一个问题,您必须启用字段映射:mapper.getConfiguration().setFieldMatchingEnabled(true);
【解决方案2】:

实际上不是单线,但这种方法不需要任何库。

我正在使用这些类对其进行测试:

  private class A {
    public int x;
    public String y;

    @Override
    public String toString() {
      return "A [x=" + x + ", y=" + y + "]";
    }
  }

  private class B {
    private int x;
    private String y;

    public int getX() {
      return x;
    }

    public void setX(int x) {
      System.out.println("setX");
      this.x = x;
    }

    public String getY() {
      return y;
    }

    public void setY(String y) {
      System.out.println("setY");
      this.y = y;
    }

    @Override
    public String toString() {
      return "B [x=" + x + ", y=" + y + "]";
    }
  }

要获取公共字段,我们可以使用反射,至于setter,最好使用bean utils:

public static <X, Y> void copyPublicFields(X donor, Y recipient) throws Exception {
    for (Field field : donor.getClass().getFields()) {
      for (PropertyDescriptor descriptor : Introspector.getBeanInfo(recipient.getClass()).getPropertyDescriptors()) {
        if (field.getName().equals(descriptor.getName())) {
          descriptor.getWriteMethod().invoke(recipient, field.get(donor));
          break;
        }
      }
    }
  }

测试:

final A a = new A();
a.x = 5;
a.y = "10";
System.out.println(a);
final B b = new B();
copyPublicFields(a, b);
System.out.println(b);

它的输出是:

A [x=5, y=10]
setX
setY
B [x=5, y=10]

【讨论】:

    【解决方案3】:

    对于仍在寻找的人, 您可以使用Gson

    尝试此操作
    Gson gson = new Gson();
    Type type = new TypeToken<YourPOJOClass>(){}.getType();
    String data = gson.toJson(workingPOJO);
    coppiedPOJO = gson.fromJson(data, type);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多