gradlemapstructimmutables-library

MapStruct and Immutables


I am having trouble getting mapstruct and immutables to work.

@Value.Immutable
public abstract class FoobarValue {
    public abstract Integer foo();
}
@Value.Immutable
public abstract class TargetFoo {
    public abstract Integer foo();
}
@Mapper
public interface ImmutableMapper {

    ImmutableMapper INSTANCE = Mappers.getMapper(ImmutableMapper.class);

    public TargetFoo toTarget(FoobarValue foobarValue);
}

Main class to test

public class FoobarValueMain {
    public static void main(String... args) {
        FoobarValue value = ImmutableFoobarValue.builder()
                .foo(2)
                .build();
        ImmutableMapper mapper = ImmutableMapper.INSTANCE;
        System.out.println(mapper.toTarget(value).foo());
    }
}

The error that I get is

Exception in thread "main" java.lang.IllegalStateException: Cannot build TargetFoo, some of required attributes are not set [foo]
    at org.play.ImmutableTargetFoo$Builder.build(ImmutableTargetFoo.java:158)
    at org.play.ImmutableMapperImpl.toTarget(ImmutableMapperImpl.java:21)
    at org.play.FoobarValueMain.main(FoobarValueMain.java:12)

My build.gradle is as follows

ext {
    mapstructVersion = "1.4.0.Beta2"
    immutablesVersion = "2.8.2"
}

dependencies {
    annotationProcessor "org.immutables:value:$immutablesVersion" // <--- this is important
    annotationProcessor "org.mapstruct:mapstruct-processor:1.4.0.Beta2"

    compileOnly "org.immutables:value:$immutablesVersion"
    implementation "org.mapstruct:mapstruct:${mapstructVersion}"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

As per reference this should all work out of the box. What am I missing here ?


Solution

  • The reason why it doesn't work is because you are not using the JavaBean convention.

    You need to prefix your methods with get

    e.g.

    @Value.Immutable
    public abstract class TargetFoo {
        public abstract Integer getFoo();
    }