In this post under MapStruct, I will show with example how to use java abstract class as Mapper interface.
In all my previous posts under MapStruct, I have shown you how to create Mapper interface (interface annotated with @Mapper annotation) using java interface.
In this class I will use java abstract class to define the Mapper interface instead of using java interface.
For our example, lets assume we have to map source class “Student” object to destination class “StudentDTO” object.
Below is the class structure of “Student” and “StudentDTO”
Student
package package17;
public class Student {
private int id;
private String name;
private String className;
//Removed getter, setter and toString method for brevity
}
StudentDTO
package package17;
public class StudentDTO {
private int id;
private String name;
private String className;
//Removed getter, setter and toString method for brevity
}
Please note for simplicity we keep the field names in both classes same.
As a result MapStruct will map properties of “Student” object to properties of “StudentDTO” object of same name.
Below is the code showing abstract class being declared as Mapper interface.
StudentMapper
package package17;
import org.mapstruct.Mapper;
@Mapper
public abstract class StudentMapper {
abstract StudentDTO getDTOFromModel(Student student);
}
Below is the main class showing how to use the “StudentMapper” abstract class
Main class
package package17;
import org.mapstruct.factory.Mappers;
public class Example17 {
public static void main(String[] args) {
StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
Student student = new Student();
student.setClassName("X");
student.setName("John");
student.setId(1);
StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
System.out.println(studentDTO);
}
}
In this way we can use java abstract class as Mapper interface instead of using java interface.