Mapping using direct field access

In all my previous post under MapStruct, in the examples I showed MapStruct used to call public getter and setter methods to map data from one object to another.

It is not compulsory that we should always have public getter and setter methods.

MapStruct can directly access the fields if they are marked “public” or “public final” and those fields don’t have public accessor methods.

I will show an example which will demonstrate this point.

For example I will use the below Pojo class.

Student

package package10;

public class Student {
    public int id;
    public String name;
    public String className;

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.id).append(":");
        stringBuilder.append(this.name).append(":");
        stringBuilder.append(this.className);
        return stringBuilder.toString();
    }
}

StudentDTO

package package10;

public class StudentDTO {
    public int id;
    public String name;
    public String className;

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.id).append(":");
        stringBuilder.append(this.name).append(":");
        stringBuilder.append(this.className);
        return stringBuilder.toString();
    }
}

As you can see in the above two Pojo classes they are no getter and setter methods. They are only 3 fields marked public and a “toString” method.

Below is the Mapper interface.

StudentMapper Interface

package package10;

import org.mapstruct.Mapper;

@Mapper
public interface StudentMapper {
    StudentDTO getDTOFromModel(Student student);
}

Below is the main method for your reference

Main class

package package10;

import org.mapstruct.factory.Mappers;

public class Example10 {
    public static void main(String[] args) {
        StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
        Student student = new Student();
        student.id = 1;
        student.name = "John";
        student.className = "X";

        StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
        System.out.println(studentDTO);
    }
}

Below is the output

Output

1:John:X

In this way, we can map data from one object to another without using public getter and setter methods.

Leave a comment