在做了一些阅读之后,似乎可以使用 & 运算符来要求多个扩展:Class<T extends Class1 & Class2> classObj;
但是,我正在寻找一种在编译时强制执行“非”功能的方法。我有香蕉扩展水果的例子。但是,我追求的是:
public abstract class Fruit
{
public abstract String getFlavour();
}
public class Lemon extends Fruit
{
@Override
public String getFlavour()
{
return "sour";
}
}
public abstract class Banana extends Fruit
{
@Override
public String getFlavour()
{
return "very sweet!";
}
public abstract String getBananaRipeness();
}
public class UnripeBanana extends Banana
{
@Override
public String getBananaRipeness()
{
return "unripe";
}
}
...
public String methodThatTakesFruitClassButNotBanana( Class<? extends Fruit ! Banana> fruitClass )
{
Fruit fruit = fruitClass.newInstance();
return fruit.getFlavour();
}
...
methodThatTakesFruitClassButNotBanana( Lemon.class ); // I want this to compile.
methodThatTakesFruitClassButNotBanana( UnripeBanana.class ); // I want this not to compile.
显然Class<? extends Fruit ! Banana>
不是有效的语法。你会推荐什么方法来在编译时强制执行这种类型的层次结构?