Java Generics,将类型限制为' self'类型
这是一个相当专业的问题,我怀疑是否有解决方案。
我有一个类型的层次结构,例如{},b扩展了A {},C扩展了A {}。 A定义抽象方法< t扩展A> t刻度(双V)
。
问题是T并未锚定,您可以将结果分配给任何类型。
通过将“自我”类型声明为通用参数:
class A<T extends A<T>> { T scale(double v) { ... ;} }
class B extends A<B> {}
class C extends A<C> {}
另一个解决方案是在每个子类中编写比例尺方法:
class A<T extends A<T>> { A scale(double v){...} }
class B extends A<B> { B scale(double v) { super.scale(v);}}
class C extends A<C> { C scale( double v) { super.scale(v);} }
但是,这是丑陋的,很多工作。
我不明白为什么编译器无法解决这个问题。 (我可能缺少某些东西。)我想要的是这样的东西:
class A { this scale(double v); }
现在这显然不起作用,但我想知道人们是否发现了有趣的通用骇客来约束通用返回类型或通用参数,观察。
This is a rather specialized question and I doubt there is a solution.
I've got a type hierarchy like A {}, B extends A{}, C extends A {}. A defines an abstract method <T extends A> T scale(double v)
.
The problem is that T is not anchored and you can assign the result to any type.
The solved this problem in enum (and that is why I think there is no solution) by declaring the 'self' type as a generic parameter:
class A<T extends A<T>> { T scale(double v) { ... ;} }
class B extends A<B> {}
class C extends A<C> {}
Another solution would be to write the scale method in each subclass:
class A<T extends A<T>> { A scale(double v){...} }
class B extends A<B> { B scale(double v) { super.scale(v);}}
class C extends A<C> { C scale( double v) { super.scale(v);} }
However, this is all ugly and lots of work.
I do not see why the compiler could not solve this problem. (I am probably missing something.) What I would like is something like this:
class A { this scale(double v); }
Now this clearly does not work but I wonder if people found interesting generic hacks to constrain a generic return type or a generic parameter to the 'current' type the compiler observes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论