Java F-Bound 通过接口(interface)绑定(bind)

标签 java generics type-systems f-bounded-polymorphism

表示法:Inter是接口(interface); Abs[N] 是一个抽象类。

以下代码在 Java 中运行良好,没有问题:

public class Impl<T extends Abs1<T>> extends Abs2<T> {...}

但是,如果你想在T上引入另一个接口(interface)绑定(bind),我还没有找到任何简单的方法来做到这一点,即:

public class Impl<T extends Inter & Abs1<T>> extends Abs2<T> {...}

不起作用,因为 Abs1 作为抽象类不能用作边界参数。我发现的最简单但丑陋(丑陋吗?)的解决方案是:

public class Impl<B extends Inter, T extends Abs1<B>> extends Abs2<T> {...}

我有预感,在具有这些特征的 Scala 中存在更优雅的解决方案,但是对于 Java 有什么技巧吗?

最佳答案

哦天哪...好吧,这太尴尬了。我太专注于 F-Bound,以至于忘记了它直接来自 JLS, section 4.4 :

Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:

  • a single type variable T, or

  • a class or interface type T possibly followed by interface types I1 & ... & In.

换句话说,(抽象)类声明必须出现在交集类型中。所描述的行为与 F-Boundedness 无关。即,以下作品:

public class Impl<T extends Abs1<T> & Inter> extends Abs2<T> {...}

Java Tutorial 中也对此进行了描述。如果有人想一想,它是不言自明的,因此解析器有一种简单的方法来检查双重继承(这是被禁止的)。

关于Java F-Bound 通过接口(interface)绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274896/

相关文章:

java - 在Java中的方法/函数中计算totalPrice

java - 如何在旧版本的 Android 操作系统中使用 API V2 显示 GoogleMap(iam 使用 map fragment )

swift - 是否可以向 Swift 协议(protocol)一致性扩展添加类型约束?

c# - MEF 2,带有实现类的通用导入

java - 为游戏设计元素库存系统并遇到问题

Java集合排序和自定义排序-速度

typescript 参数相互依赖

c# - GetGenericTypeDefinition 返回不同的类型

generics - 为什么类型参数在 TypeScript 中消失了?

haskell - 为什么我不能使 String 成为类型类的实例?