我正在尝试设计一个可以应用于声明类型的子类的arg函数:
但是当我将这样的函数应用于类型T时,如下所示:
Function<? extends T,Boolean> function;
function.apply(T)
我收到以下编译错误:
T cannot be converted to capture#2 of ? extends T
我试图设计的验证界面示例:
//Intent is that the function can be applied to T, or any subclass of T
public interface IBeanValidator<T> {
public Function<? extends T, Boolean> getValidation();
}
//Class that implements this interface will accept validators for its type
public interface IValidateableBean<T> {
public void validate(final IBeanValidator<T> validator);
}
//Interface for bean objects, which can be validated with validators designed
//for beans belong to this inheritane hierarchy
public interface IBean extends IValidateableBean<IBean> {
public default void validate(final IBeanValidator<IBean> validator) {
//compilation error occurs here.
validator.getValidation().apply(this);
}
}
答案 0 :(得分:1)
而不是Function<? extends T, Boolean>
,您实际上只需要一个Function<T, Boolean>
,其中将接受T的子类型。Function<? extends T, Boolean>
实际上是指一些未知但具体的T
的子类型,例如Function<SubT, Boolean>
,不一定适用于任何T
。