问题描述
没有静态成员可以使用类型参数,但可以使用泛型类型参数调用静态成员吗?例如: -
抽象类代理< A> {
void callAgent();
Agent(){
A.add();
$ b $ p
$ b这里add()是一个静态方法。 p>
对于类似的话题,有一些C#的问题和答案,但我不太清楚在Java中如何去做。
解决方案不,你不能这样做,如果A是一个泛型类型。 (Bozho的回答很快:)并且可能认为A是具体类型。
以下是一些工作内容。
抽象类代理扩展Blah< ConcreteA> {
void callAgent();
Agent(){
ConcreteA.add();
}
}
但它可能不是你想要做的。
阅读完您的评论后,听起来像是您真正想要做的是:
抽象类Agent< A extends SomeClassThatSupportsAdd> {
void callAgent();
protected abstract createNew();
Agent(){
A a = createNew();
A.add();
$ b你的子类必须覆盖 createNew()
。
如果你还不喜欢,你可以看看AspectJ,它可以让你做一些构造函数(看看@Configurable是如何做到这一点的),但这会变得更加复杂和复杂。
另一个选项是Scala。 Java不会对静态方法进行继承,因此您无法获得参数化模块(某些语言中的函数组称为functor ... ocaml)。然而,Scala支持一个允许参数化函数多态继承的单例对象。
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();
}
}
Here add() is a static method.
There are some C# questions and answers on a similar topic but I'm not too sure how to go about it in Java.
解决方案 No you cannot do it if A is a generic type. (Bozho answered to fast :) and probably thought A was concrete type.
What will work is the following.
abstract class Agent extends Blah<ConcreteA>{
void callAgent();
Agent() {
ConcreteA.add();
}
}
but it's probably what 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();
}
}
Your subclasses will have to override createNew()
.
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 more trickier and complicates things.
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.
这篇关于使用泛型类型调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!