有没有办法创建绑定到泛型参数的泛型方法?在我的示例下面:
class Taste {}
class Vanilla extends Taste {}
class Chocolate extends Taste {}
class IceCream<T extends Taste> {
int tasteLevel = 0;
//only this taste can be used
void enhanceTaste(T taste) {
tasteLevel++;
}
}
class ChocolateIceCream extends IceCream<Chocolate> {}
class VanillaIceCream extends IceCream<Vanilla> {}
这是实现通用方法 enhanceTastes()的类。
是否可以将方法参数 taste 绑定到 _iceCreamList 口味?
也许是一种定义“ T = I
class IceCreamBox<T extends IceCream> {
List<T> _iceCreamList = List<T>();
//GENERIC METHOD
void enhanceTastes<E extends Taste /*of _iceCreamList*/>(E taste) {
for (T iceCream in _iceCreamList) {
iceCream.enhanceTaste(taste);
}
}
}
这是测试。 box.enhanceTastes(Vanilla())不允许。
class TestBox {
void test() {
IceCreamBox<ChocolateIceCream> box = IceCreamBox<ChocolateIceCream>();
box.enhanceTastes(Chocolate()); //OK
box.enhanceTastes(Vanilla()); //I WANT THE COMPILER TO COMPLAIN! BECAUSE THIS IS A CHOCOLATE ICE CREAM BOX!
}
}