LongProperty 为什么要实现 Property<Number>但不是 Property&lt;Long&gt;? [英] Why does LongProperty implement Property&lt;Number&gt; but not Property&lt;Long&gt;?

查看:21
本文介绍了LongProperty 为什么要实现 Property<Number>但不是 Property&lt;Long&gt;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaFX API 中发现了一个奇怪的地方:LongProperty 实现了 Property,但没有实现 Property.

I have come across what seems like a peculiarity in the JavaFX API: LongProperty implements Property<Number>, but not Property<Long>.

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

What is the reason for this? I sort of get the idea that it all stems from Java's inherent problem with covariance and contravariance, because generics where implemented stupidly via erasure, to maintain backwards compatibility with the bytecode; but what problem could have arisen by having LongProperty implement both Property<Number> and Property<Long>?

这个问题源于这个问题:Apply LongProperty to TableColumn programmatically (vs 语义)

This question originated from this problem: Apply LongProperty to TableColumn programmatically (vs semantically)

推荐答案

不能同时实现.

为此,它需要在使用泛型的接口中实现每个方法的两个版本.我们以一个为例:

To do that, it would need to implement two versions of each method in the interface that uses the generic. Let's take one as an example:

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

在幕后,擦除意味着这被编译为:

Under the hood, erasure means this gets compiled down to:

bindBidirectional(Property other) { ... }

那么,实现 PropertyProperty 的东西会做什么?它将有两种方法:

So then, what would something that implements Property<Number> and Property<Long> do? It would have two methods:

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

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

... that would compile down, after erasure, to two methods:

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

这两个方法有冲突,运行时无法解决.

These two methods conflict, and there'd be no way to resolve them at runtime.

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

Even if you used some compiler trickery to get around this, what happens when someone uses LongProperty as a raw Property?

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

无法知道这意味着要解析到两个 bindDirectional 变体中的哪一个.

There's no way to know which of the two bindDirectional variants this is meant to resolve to.

这篇关于LongProperty 为什么要实现 Property<Number>但不是 Property&lt;Long&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆