Java通用类型 [英] Java generic type
问题描述
当我有一个接口的时候
public interface Foo< T> {
T someMethod();
}
有没有什么办法可以保证当某个类实现了这个接口时,泛型类型是相同的实现类。
例如:
public class Bar实现Foo< Bar> {
Bar someMethod(){
return new Bar();
}
}
< (在下面的例子中)。(在C ++世界中,这被称为 (注意第二次提到 另外, 我想说,以上是故事的结尾,但tangens在他们的修订中正确地指出它不完全健壮,并且与他们的回答完全不同。 有是我有的 使用 When I have an interface is there any way to assure that when some class implements this interface then generic type is the same implementig class. For example:
Yes, this can be done (sort of; see below). (In the C++ world, this is called the "Curiously Recurring Template Pattern", but it applies in Java too): (Note the second mention of Also, this is how I'd like to say that the above is the end of the story, but tangens rightly points out in their revision that it's not totally robust, and really not all that different from their answer in character. There is one difference (that I can think of) between the With In closing, go ahead and upvote tangens's answer too, if you can. (tangens, you should touch your post so I can upvote you too.) They have a very good point, and I'm sorry that I missed it the first time around. Thanks, tangens! 这篇关于Java通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
public interface Recur< T扩展Recur< T>> {
// ...
}
T
。这是CRTP的一个重要组成部分。)
定义了java.util.Enum
,这样一个名为 Foo
的枚举类型必须从 Enum
,所以它在Java中也不罕见。
Recur< T>
解决方案和 Recur<> $ c之间的一个区别(我能想到) $ c $> tangens的解决方案:
public interface Recur< T extends Recur< T>> {
T foo();
}
class A实现了Recur< B> {
@Override
public B foo(){
return new B();
}
}
class B实现了Recur< A> {
@Override
public A foo(){
return new A();
< T>
,上面不会编译;与<?>
,它会。但那只是分裂头发。它不会改变tangens的中心点,即给定一个已经有效的 Recur
实现,你可以让后续的实现使用已经有效的类型,而不是自己。我仍然认为这是值得的,但是这不值得比tangens的回答更重要。public interface Foo<T> {
T someMethod();
}
public class Bar implements Foo<Bar> {
Bar someMethod() {
return new Bar();
}
}
public interface Recur<T extends Recur<T>> {
// ...
}
T
. That's an essential part of the CRTP.)java.util.Enum
is defined, so that an enum type called Foo
must derive from Enum<Foo>
, so it's not an uncommon pattern in Java either.
Recur<T>
solution I have, and the Recur<?>
solution that tangens has:public interface Recur<T extends Recur<T>> {
T foo();
}
class A implements Recur<B> {
@Override
public B foo() {
return new B();
}
}
class B implements Recur<A> {
@Override
public A foo() {
return new A();
}
}
<T>
, the above would not compile; with <?>
, it would. But that's just splitting hairs; it doesn't change tangens's central point which is that given an already valid Recur
implementation, you can make subsequent implementations use the already-valid type, rather than itself. I still say that's worth something, but that's not worth any more of a something than tangens's answer.