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.

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()

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.

Leave a ReplyCancel reply