Skip to content
Advertisement

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

Let’s suppose I have classes:

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

public class B extends A {
  public String z;
}

I have an instance of B called b and want to map to A (to get rid of z property as it’s getting serialized later). I was trying to do;

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

But as a result I am getting the the same type B object. I suspect it could be because B is a subclass of A, so there is no point in converting types, because B satisfies A, but it’s just my suspicion.

Can I somehow tell ModelMapper do convert the type to the exact one I want? Maybe there is a better way of doing that?

Advertisement

Answer

You can do this with a custom TypeMap

Conside the following example code:

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));

With output:

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
Advertisement