Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method using generic type

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.

like image 360
aps Avatar asked Jun 28 '11 19:06

aps


2 Answers

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 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 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.

like image 107
Adam Gent Avatar answered Sep 24 '22 23:09

Adam Gent


No, you cannot. The compiler does not know A (which resolves to Object) has the add method.

And you shouldn't need to invoke static methods on generic types in the first place. If you want specific behaviour for each type, define it as non-static, use extends BaseClass in the generics declaration, and invoke it.

Technically, you can also invoke a static method that way, but it's ugly:

class Base {
    public static void add() { }
}

class Foo<A extends Base> {
    void bar() {
        A a = null; // you can't use new A()!
        a.add();
    }
}
like image 42
Bozho Avatar answered Sep 25 '22 23:09

Bozho