使用泛型调用静态方法

编程入门 行业动态 更新时间:2024-10-28 18:22:57
本文介绍了使用泛型调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

没有静态成员可以使用类型参数,但是否可以使用泛型类型参数调用静态成员?例如:-

No static member can use a type parameter, but is it possible to call a static member using the generic type parameter? For example:-

abstract class Agent<A>{ void callAgent(); Agent(){ A.add(); } }

这里的 add() 是一个静态方法.

Here add() is a static method.

有一些关于类似主题的 C# 问题和答案,但我不太确定如何在 Java 中进行.

There are some C# questions and answers on a similar topic but I'm not too sure how to go about it in Java.

推荐答案

不,如果 A 是泛型类型,你不能这样做.(Bozho 回答很快 :) 并且可能认为 A 是具体类型.

No you cannot do it if A is a generic type. (Bozho answered to fast :) and probably thought A was concrete type.

以下是有效的.

abstract class Agent extends Blah<ConcreteA>{ void callAgent(); Agent() { ConcreteA.add(); } }

但这可能不是您想要做的.

but it's probably not what you want to do.

阅读您的评论后,您似乎真正想做的是:

After reading your comments it sounds like what you really want to do is:

abstract class Agent<A extends SomeClassThatSupportsAdd> { void callAgent(); protected abstract A createNew(); Agent() { A a = createNew(); A.add(); } }

您的子类必须覆盖 createNew().

如果你仍然不喜欢那样,你可以看看 AspectJ,它允许你做一些构造函数的魔法(看看 spring 如何做@Configurable),但这会变得更加棘手和复杂.

If you still do not like that you can take a look at AspectJ which will allow you to do some constructor magic (see how spring does @Configurable) but that gets far trickier and complicates things.

另一种选择是 Scala.Java 不对静态方法进行继承,因此您无法获得参数化模块(某些语言中的函数组,这称为函子 ... ocaml).然而,Scala 支持一个允许参数函数多态继承的单例对象".

Another option is Scala. Java does not do inheritance on static methods so you can't get parameterized modules (groups of functions in some languages this is called a functor ... ocaml). However Scala supports a singleton "object" that does allow for parametric functional polymorphic inheritance.

更多推荐

使用泛型调用静态方法

本文发布于:2023-11-10 10:23:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575095.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!