我目前遇到了Lombok的@SuperBuilder注解和泛型的问题。我有一个抽象的父类和一个final的子类。当使用builder创建子类时,传递正确类型的值会导致编译错误。
简化后的类和接口如下:
如果工作正常,那么子类本身就不再具有通用参数。所以像这样拥有子类,一切都可以编译并且完美运行。
简化后的类和接口如下:
@SuperBuilder(toBuilder = true)
public abstract class Parent<T> {
private SomeGenericClass<?, Parent<T>> someGenericClass;
private T value;
}
interface SomeInterface<D> {
}
class SomeGenericClass<D, S> implements SomeInterface<D> {
}
@SuperBuilder(toBuilder = true)
final class Child<T> extends Parent<T> {
}
测试代码
public class SuperBuilderTest {
public static void main(String[] args) {
SomeGenericClass<String, Parent<Long>> someGenericClass = new SomeGenericClass<>();
Child<Long> child = Child.builder()
.someGenericClass(someGenericClass) // error: The method someGenericClass(SomeGenericClass<?,Parent<Object>>) in
// the type Parent.ParentBuilder<Object,capture#1-of ?,capture#2-of ?> is
// not applicable for the arguments (SomeGenericClass<String,Parent<Long>>)
.value(10L) // error: Type mismatch: cannot convert from capture#1-of ? to Child<Long>
.build();
}
}
如果工作正常,那么子类本身就不再具有通用参数。所以像这样拥有子类,一切都可以编译并且完美运行。
@SuperBuilder(toBuilder = true)
final class Child extends Parent<Long> {
}
我是在做错什么还是使用 @SuperBuilder
时无法有通用的 final
类呢?