将派生 class 映射到基础 class 时,ModelMapper 返回源对象类型

ModelMapper returning source object type when mapping derived class to a base class

假设我有 类:

public class A {
  public String x;
  public String y;
}

public class B extends A {
  public String z;
}

我有一个名为 bB 实例,我想映射到 A(在序列化时摆脱 z 属性之后)。 我正在尝试做;

new ModelMapper().map(b, A.class)

但结果我得到了相同类型的 B 对象。我怀疑可能是因为B是A的子类,所以转换类型没有意义,因为B满足A,但这只是我的怀疑。

我能以某种方式告诉 ModelMapper 将类型转换为我想要的类型吗?也许有更好的方法?

您可以使用自定义 TypeMap

考虑以下示例代码:

B b = new B();
A a = new ModelMapper().map(b, A.class);
System.out.println("Converted to A? = " + a);
System.out.println("Still instance of B? " + (a instanceof B));

ModelMapper modelMapper = new ModelMapper();
// Creates a base TypeMap with explicit mappings
modelMapper.createTypeMap(B.class, A.class);
A a2 = modelMapper.map(b, A.class);
System.out.println("Converted with TypeMap to A? = " + a2);
System.out.println("Still instance of B? " + (a2 instanceof B));

输出:

Converted to A? = tests.so.modelmapper.B@d3bd8b
Still instance of B? true

Converted with TypeMap to A? = tests.so.modelmapper.A@56dfcb
Still instance of B? false