什么';这个Java装饰器泛型类有什么问题?
我创建了一个Java类,用泛型装饰另一个接口。但是,它总是有一些编译器错误。这是可以重现错误的定制示例代码什么';这个Java装饰器泛型类有什么问题?,java,generics,decorator,Java,Generics,Decorator,我创建了一个Java类,用泛型装饰另一个接口。但是,它总是有一些编译器错误。这是可以重现错误的定制示例代码 public interface GenericInterface<T> { <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction); } class GenericClass<T> imple
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);
});
}
}
公共接口通用接口{
GenericInterface testFunc(双函数记住,?
就像一个一次性使用的新类型变量
因此,参数的双函数
泛型中的?super T
不必与?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);
}
@覆盖
public GenericInterface testFunc(BiFunctionInterface testFunc)很有趣。看起来Java只是放弃了类型推断而采用了Object。我无法猜测原因。FWIW您可以为lambda(t,U)->{…}提供显式类型
它会编译,但这仍然是一个很好的问题。非常有趣,它似乎接受了T
很好。你也可以将u
转换为u
,但是…非常混乱。你能澄清为什么编译器对第一个参数T
没有问题,但对第二个u
有问题吗?