Java Generics,将类型限制为' self'类型

发布于 2025-02-09 23:17:58 字数 772 浏览 0 评论 0原文

这是一个相当专业的问题,我怀疑是否有解决方案。

我有一个类型的层次结构,例如{},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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文