Home > other >  Error with Lombok's @Builder with generic typed field
Error with Lombok's @Builder with generic typed field

Time:09-27

I am having issues creating a POJO using Lombok's @Builder annotation and have it map to the expected type at runtime.

Here's my code:

OperationResult.java

import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class OperationResult<D>
{
    private D data;
}

OperationResultTest.java

import org.junit.jupiter.api.Test;
public class OperationResultTest
{
    @Test
    public void testGenerics()
    {
        OperationResult<String> restult = OperationResult.builder()
            .data("Test")
            .build();
    }
}

This results in a compilation error stating the returned type is OperationResult<Object> and cannot be casted to the expected type of OperationResult<String>.

Is it possible to use generics and know the returned type using Lombok's @Builder annotation?

Thanks for your help!

CodePudding user response:

To resolve the compilation error, you should define the generic when calling the builder() method like so:

OperationResult<String> result = OperationResult.<String>builder()
    .data("Test")
    .build(); 
  • Related