鉴于以下情况,只能编写适用于 SpecificModel
的模型处理程序,不可能拥有仅处理模型的模型处理程序。但是,当我们删除 T extends Model
表达式时,创建非法内容将变得非常容易。
public interface Model {}
public class SpecificModel implements Model {}
public interface ModelHandler<T extends Model>
{
void handleModel(T model);
}
是否有可能写出像T extends Model || 这样的结构?型号
?所以 T
必须 extend Model
或者如果处理程序不知道 Model
的子类型,则必须是 Model
本身>?
谢谢!
最佳答案
引自 Effective Java,作者 Joshua Bloch 关于 <? extends E>
符号:
The use of the keyword extends is slightly misleading: recall [from Item 26] that subtype is defined so that every type is a subtype of itself, even though it does not extend itself.
因此写作 <T extends Model>
等同于您所期望的:<T extends Model || Model>
.
关于java - 是否可以编写允许类型的子类型和类型本身的 Java 泛型表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7022786/