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

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

问题描述

我遇到了类似于JavaFX API的特性: LongProperty implements Property< Number> ,但不是属性< Long>



这是什么原因?我认为这一切都源于Java的协变和逆变的内在问题,因为通过擦除实现 的泛型,保持与字节码的向后兼容性;但是 LongProperty 实现 Property< Number> Property< Long>



编辑:这个问题来自这个问题:以编程方式将LongProperty应用于TableColumn(vs semantically)

解决方案

不能实现两者。为此,它需要实现两个使用通用接口的每个方法的版本。让我们以一个为例:

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

在这种情况下,擦除意味着将其编译为:

 bindBidirectional(Property other){...} 

,实现 Property< Number> Property< Long> 的事情会做什么?它有两种方法:

  bindBidirectional(Property< Long> other){...} 
bindBidirectional(Property< ;数字>其他){...}

...在删除后,到两个方法:

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

这两种方法是冲突的,在运行时将无法解决它们。 / p>

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

 属性rawLongProperty = new LongProperty(); 
rawLongProperty.bindBidirectional(someOtherRawProperty);

无法知道两个 bindDirectional 变体,这是为了解决。


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

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>?

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

解决方案

It can't implement both.

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) { ... }

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.

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);

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

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

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