繁体   English   中英

将 pojo 字段复制到另一个 pojo 的 setter

[英]Copy pojo fields to another pojo's setters

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

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

至少在默认设置下,Dozer 的

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

不会正确复制字段。

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

我建议你使用:

http://modelmapper.org/

或者看看这个问题:

通过反射将一个类中字段的所有值复制到另一个类中

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

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

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

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

  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]

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

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

暂无
暂无

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

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