Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error with Lombok's @Builder with generic typed field

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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(); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading