本文介绍了在泛型中接受自己作为类型参数的用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个无关的问题上看到了一些代码,但它让我好奇,因为我从来没有见过这样的Java泛型构造。创建一个可以作为类型参数本身或其后代自身的泛型类的用法是什么?下面是例子:

 抽象类A< E extends A< E>> {
abstract void foo(E x);
}

首先想到的是一个列表,参数。使用这段代码感觉很奇怪,你如何声明A类型的变量?递归声明!?



这甚至可以工作吗?如果你们中的任何一个人在代码中看到这种情况?它是如何使用的?






编辑

我的问题是一样的只是措辞不同,但该问题的答案将回答我的

另外感谢您对,它给出了一些历史背景和对这个主题的进一步解释。



这个旧的可能给我们提供了最好的解释,我为我们找到了Java家伙。

现在很难在这里选择一个正确的答案,因为它们都很有帮助,所以我会选择一个能够产生最多阅读材料的答案(参考上文)。

解决方案

泛型不是牛逼只是像列表容器。这种自身扩展类型参数用于让超类在方法参数和返回类型等地方引用子类,即使在编译超类时没有实际的特定子类可用。它类似于C ++中的。



您的示例的子类将被声明为

  class Foo extends A< Foo> 

和继承的 foo()方法变成

  void foo(Foo x)

查看 A 如何定义一个方法,该方法使用 Foo 参数,即使它没有实际上并不知道 Foo



是的,这类事情并不常见,但并非前所未闻:内置的类使用类似诀窍。

I saw some code on an unrelated question but it got me curious as I never saw such construct with Java Generics. What would be the use of creating a generic class that can take as type argument itself or descendants of itself. Here is example :

abstract class A<E extends A<E>> {
    abstract void foo(E x);
}

the first thing that came to mind would be a list that takes a list as parameter. Using this code feels strange, how do you declare a variable of type A ? Recursive declaration !?

Does this even work ? If so did any of you see that in code ? How was it used ?


EDIT

Indeed it turns out my question is the same as this one only phrased differently, but the answers for that question will answer mine as well.

Also thanks for the reference to the Curiously Recurring Template Pattern which gives some historical background and further explanations on the subject.

This old blog entry probably gives the best all around explanation I found for us Java guys.

Now hard to choose a right answer here for they are all helpful, so I will go for the one that ended up yielding the most reading material (referenced above)

解决方案

Generics aren't just for containers like lists. This sort of "extends itself" type parameter is used to let the superclass refer to the subclass in places like method parameters and return types, even though no actual specific subclass is available when the superclass is compiled. It's analogous to the curiously recurring template pattern in C++.

A subclass of your example would be declared as

class Foo extends A<Foo>

and the inherited foo() method becomes

void foo(Foo x)

See how A defined a method that takes a Foo parameter even though it doesn't actually know about Foo?

Yes, this sort of thing is unusual, but not unheard of: the built-in Enum class uses a similar trick.

这篇关于在泛型中接受自己作为类型参数的用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:13