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

Syntax error for lombok Generic class , builder pattern and custom setter

Following are the set of classes.

import lombok.Builder;
import lombok.Data;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Data
@Builder
public class GenericClass<T> {

    //Omitted other attributes for brevity.

    private Class<T> elementClazz;

    @SuppressWarnings("rawtypes")
    private Class<? extends Collection> collectionClazz;

    private Collection<String> strings;


    /*BUILDER*/
    public static class GenericClassBuilder {
        public GenericClassBuilder strings(Collection<String> strs) {
            if (strs == null)
                strs = Collections.emptyList();
            this.strings = strs;
            return this;
        }
    }


}

@Data
class SomeClass {
    private int number;
}

class Main {
    public static void main(String[] args) {
        GenericClass.<SomeClass>builder().elementClazz(SomeClass.class).collectionClazz(List.class).build();
    }
}

But I see syntax error in .elementClazz(SomeClass.class). However this goes away if I remove the custom setter method in builder class.

How do I make this work?

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

>Solution :

For a generic class, lombok will generate a generic builder class. After all, how would the builder know what type parameters the type it is building has, otherwise? The builder class is static, so it can’t access the type parameter declared in the outer class.

As you probably know, if you declare the builder class with the matching name yourself, lombok will not generate the builder class again, and would directly inject the builder methods into the class you wrote.

However, since your class is not generic, it fails to compile when Lombok generates methods that have a T in it.

IntelliJ also seems to be confused about the elementClazz(SomeClass.class) call, since elementClazz is supposed to take a Class<T>, but T doesn’t exist since the builder isn’t generic. Therefore, it seems to think that T is not SomeClass but some other random type, giving you the error you see.

In short, just make the builder class generic:

public static class GenericClassBuilder<T> {
    public GenericClassBuilder<T> strings(Collection<String> strs) {
        // ...
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