6

There are two source classes A and B

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

class B {
    public Double x;
    public Double y;
}

and another target class C

class C {
    public Double x;
    public Double y;
}

It is clear how to map A to C or B to C.

Is it possible to map some function, for example, addition or pow of source objects to the target one so that the generated code will look like this

C.x = A.x + B.x
C.y = A.y + B.y

or

C.x = Math.pow(A.x, B.x)
C.y = Math.pow(A.y, B.y)

1 Answer 1

4

This can be done by using expressions.

@Mapper
public interface MyMapper {

    @Mapping(target = "x", expression = "java(a.x + b.x)")
    @Mapping(target = "y", expression = "java(a.y + b.y)")
    C map(A a, B b);
}

or

@Mapper
public interface MyMapper {

    @Mapping(target = "x", expression = "java(Math.pow(a.x, b.x))")
    @Mapping(target = "y", expression = "java(Math.pow(a.y, b.y))")
    C map(A a, B b);
}

More info about expressions can be found in the reference documentation here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.