如何使用MapStruct应用两个参数映射对象的功能?

时间:2017-06-28 17:37:41

标签: java mapstruct

有两个源类A和B

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

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

和另一个目标类C

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

很清楚如何将A映射到C或B到C.

是否可以将某些函数(例如,源对象的添加或幂)映射到目标函数,以便生成的代码看起来像这样

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

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

1 个答案:

答案 0 :(得分:1)

这可以通过使用表达式来完成。

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

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

有关表达式的更多信息,请参阅参考文档here