gpt4 book ai didi

java - 这个 Java 装饰器泛型类有什么问题?

转载 作者:行者123 更新时间:2023-12-03 22:59:20 25 4
gpt4 key购买 nike

我创建了一个 Java 类来用泛型装饰另一个接口(interface)。但是,它总是有一些编译器错误。这是可以重现错误的定制示例代码。

public interface GenericInterface<T> {
<U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction);
}

class GenericClass<T> implements GenericInterface<T> {

private GenericInterface<T> delegate;
public GenericClass(GenericInterface<T> dele) {
this.delegate = dele;
}

@Override
public <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction) {
GenericClass<T> impl = new GenericClass<T>(delegate);
return impl.testFunc((t, u) -> {
// Do something here ...
// ...
// Error for argument u: Required type: capture of ? super U, Provided: Object
return biFunction.apply(t, u);
});
}
}
我尝试了整整一周,无法弄清楚它有什么问题。实际上,我是高级 Java 泛型的新手。

最佳答案

请记住,?就像一个一次性的新类型变量。
因此,? super T在你的论点中 BiFunction泛型,不必与 ? super T 的类型相同根据 testFunc 的要求调用。
这是可以修复的:

@Override
public <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction) {
GenericClass<T> impl = new GenericClass<T>(delegate);
BiFunction<T, U, V> b = (t, u) -> {
// do something
return biFunction.apply(t, u);
};
return impl.testFunc(b);
}

关于java - 这个 Java 装饰器泛型类有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67099924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com