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?
>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) {
// ...