使用泛型调用静态方法 [英] Calling a static method using generic type

查看:55
本文介绍了使用泛型调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用泛型调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆