我遇到了 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/