java - 为什么 LongProperty 实现了 Property<Number> 而不是 Property<Long>?

标签 java generics javafx

我遇到了 JavaFX API 中的一个特点:LongProperty工具 Property<Number> , 但不是 Property<Long> .

这是什么原因?我觉得这一切都源于 Java 固有的协变和逆变问题,因为泛型通过删除愚蠢地实现,以保持与字节码的向后兼容性;但是LongProperty可能会出现什么问题?同时实现 Property<Number> Property<Long>

编辑:这个问题源于这个问题:Apply LongProperty to TableColumn programmatically (vs semantically)

最佳答案

不能同时实现两者。

为此,它需要在使用泛型的接口(interface)中实现每个方法的两个版本。举个例子:

bindBidirectional(Property<Long> other) { ... }

在幕后,删除意味着它被编译为:

bindBidirectional(Property other) { ... }

那么,实现 Property<Number> 的东西会是什么?和 Property<Long>做?它有两种方法:

bindBidirectional(Property<Long> other) { ... }
bindBidirectional(Property<Number> other) { ... }

... 删除后会编译成两种方法:

bindBidirectional(Property other) { ... }
bindBidirectional(Property other) { ... }

这两个方法有冲突,并且没有办法在运行时解决它们。

即使您使用了一些编译器技巧来解决这个问题,当有人将 LongProperty 用作原始属性时会发生什么?

Property rawLongProperty = new LongProperty();
rawLongProperty.bindBidirectional(someOtherRawProperty);

无法知道这两个 bindDirectional 中的哪一个 |这是要解决的变体。

关于java - 为什么 LongProperty 实现了 Property<Number> 而不是 Property<Long>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620552/

相关文章:

java - 在异常 "throws"中使用泛型并具有 List<String> 参数的类无法编译

Java 列表参数化?

javafx - 如何在 javafx 2 中设置 splitpane 分隔线宽度

Java Fx 将场景大小调整为舞台

java - Spring mvc + Security Pdf 显示空白

java - 从 twitter4j 获取翻译数据

java - 如何在 Android 中迭代 Firebase 结构?

Java - 对多种类型使用泛型

java - 静态初始化程序中的异常处理

java - 如何在intelliJ中重构包导入