假设我有课:
public class A {
public String x;
public String y;
}
public class B extends A {
public String z;
}
我有一个B
被调用的实例,b
并且想要映射到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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句