Skip to content

Passing generic types inner class

Here is following example:

import lombok.Builder;
import lombok.Getter;
import lombok.Singular;

import java.util.List;

@Getter
@Builder
public class GenericsType<T> {

    @Singular("entry") 
    private List<Animal> list;

    @Builder
    private static class Animal<T> {
        T test;
    }

    public void main(String args[]){

        GenericsType.<String>builder()
                .entry(Animal.<String>builder().test("my object").build())
                .build();
    }
}

Is there a way just to pass the generic <String> one time? Actually the inner class should already know its type.

GenericsType.<String>builder()
                .entry(Animal.builder().test("my object").build())
                .build();

Answer

That is a limitation of the Java compiler. Although it looks obvious in this case that the type parameter must be String, inferring that is not as easy as it seems to be: The compiler has to propagate the type information backwards from build() via test("my object") to the builder() method.

New compiler versions may support such inference, but at least javac 11 does not.