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

What is the difference between a constructor and a builder when using generics?

While programming in Java, I encountered the following problem.

when use Constructor: The following code works fine.

public class Generics<T> {

    private T data;

    public static <T> Generics<T> of(T data) {
        return new Generics<>(data);
    }

    public Generics(T data) {
        this.data = data;
    }
}

when use builder: An error occurs saying that the Object type is provided as follows.

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

enter image description here

I used a builder provided by Project Lombok.

Why doesn’t the builder generic in the code above work?

>Solution :

Evidently Lombok generates a static generic builder() method. You can specify the generic type of a generic static method using <T> before the method name, as in:

return Generics.<T>builder()
          .data(data)
          .build();

If you don’t specify the generic type when you call builder(), you get a raw type, at which point generic type inference no longer works.

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