通配符上的Java语言规范 [英] Java language specification on wildcards
问题描述
我正在通过此链接(第4章.类型,值和变量),并且不理解以下几点:
I am going through this link (Chapter 4. Types, Values, and Variables) and did not understand below point:
通配符与已建立类型理论的关系是一个有趣的关系,我们在这里简要地提及.通配符是存在类型的一种受限形式.
Given a generic type declaration G<T extends B>, G<?> is roughly analogous to Some X <: B. G<X>
.
如果您提供了很好的例子来清楚地理解上述要点,我将不胜感激.
I appreciate if you provide good example to understand above point clearly.
谢谢.
推荐答案
此语句的措词和格式有点不巧 * .实际上,答案中的链接涵盖了一般主题,但您可以尝试着重于特定情况Java和通配符在这里:
The wording and formatting of this statement are a bit unlucky*. The link in the answer by Maouven actually covers the general topic pretty well, but one can try to focus on the particular case of Java and Wildcards here:
通配符是存在类型的一种受限形式.给定一个通用类型声明G,G大致类似于Some X <:B. G.
Wildcards are a restricted form of existential types. Given a generic type declaration G, G is roughly analogous to Some X <: B. G.
这基本上表示G
的类型参数是B
的任何子类型.即使您没有明确说出来,这也是总是的情况.
This basically says that the type parameter of the G
is any subtype of B
. And this is always the case, even when you don't say it explicitly.
考虑以下片段,希望可以说明这一点:
Consider the following snippet, which hopefully illustrates the point:
class B { }
class G<T extends B>
{
T get() { return null; }
}
public class Example
{
public static void main(String[] args)
{
G<?> g = null;
// This works, even though "G<?>" seemingly does not say
// anything about the type parameter:
B b = g.get();
}
}
通过调用g.get()
获得的对象的类型为B
,因为G<T extends B>
的声明保证了任何类型参数(即使它是?
通配符)总是至少"为B
类型.
The object that you obtain by calling g.get()
is of type B
, because the declaration of G<T extends B>
guarantees that any type parameter (even if it is the ?
wildcard) always be "at least" of type B
.
(与此相反:如果仅声明是G<T>
,则从g.get()
获得的类型将仅是Object
类型)
(In contrast to that: If the declaration only was G<T>
, then the type obtained from g.get()
would only be of type Object
)
与类型理论符号的关系描述为"大致类似".您可能会想像这句话:如果声明为G<T extends B>
,并且使用类型为G<?>
,则这种大致(!)的含义是:存在类型为X extends B
,此处的?
表示该类型. (未知),键入X
.
The relationship is described as "roughly analogous" to the type theoretic notation. You can probably imagine this as saying: If the declaration is G<T extends B>
, and you use the type G<?>
, then this roughly (!) means: There exists a type X extends B
, and the ?
here stands for this (unknown) type X
.
An aside: Note that this also refers to Insersection Types. If you declared the class as class G<T extends B & Runnable>
, then the statements
B b = g.get();
Runnable x = g.get();
都有效.
* 不吉利"的格式指的是该段的源代码实际读取的事实
* The "unlucky" formatting referred to the fact that the source code of this paragraph actually reads
... is roughly analogous to <span class="type">Some <span class="type">X</span> ...
更清楚地表明"Some"一词已经是在其中正式定义的 type 的一部分...
making clearer that the word "Some" already is part of the type that is being defined there formally...
这篇关于通配符上的Java语言规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!