问题描述
给定一个通用接口 interface Foo< A,B> {}
我想编写一个需要A成为B的子类的实现。要做
class Bar // - >语法错误
或
class Bar< A extends B,B>实施Foo< A,B> {}
// - >非法前向引用
但是唯一可行的解决方案是这样的:
class Bar< B,A extends B>实施Foo< A,B> {}
这很丑陋,因为它颠倒了泛型参数的顺序。
是否有任何解决方法或解决方法解决此问题?
,试着考虑 Bar
。
一个用于 Bar
的变量,首先指定父类,然后指定子类。这就是 Bar
的工作原理。不要认为它是倒退 - 认为它是前锋。父母自然应该在孩子面前指定。您添加的这种附加关系是驱动参数顺序的原因,而不是基础接口。
Given a generic interface
interface Foo<A, B> { }
I want to write an implementation that requires A to be a subclass of B. So I want to do
class Bar<A, B super A> implements Foo<A, B> { }
// --> Syntax error
or
class Bar<A extends B, B> implements Foo<A, B> { }
// --> illegal forward reference
But the only solution that seems to work is this:
class Bar<B, A extends B> implements Foo<A, B> { }
which is kind of ugly, because it reverses the order of the generic parameters.
Are there any solutions or workarounds to this problem?
Since this isn't possible in Java, try to think of Bar<B, A extends B>
differently.
When you declare a variable for Bar
, you're specifying the parent class first and then the child class. That's how Bar
works. Don't think of it as being backwards - think of it as being forwards. The parent should naturally be specified before the child. This additional relationship you added is what drives the parameter order, not the underlying interface.
这篇关于Java泛型:非法的前向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!