如何定义一个灵活地接受声明类型的子类的函数

How to define a Function which flexibly accepts subclasses of declared type

我正在尝试设计一个可应用于已声明类型的子类的 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);
    }
}

而不是 Function<? extends T, Boolean>,您实际上只需要 Function<T, Boolean> 接受 T 的子类型。Function<? extends T, Boolean> 实际上是指T 的一些未知但特定的子类型,例如Function<SubT, Boolean>,不一定适用于任何 T