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.
It is handy to get a value from an enum you don't know beforehand.
Having:
You can do:
I guess you can also take advantage of this in your own classes, although I would not recommend using
static
too much.No, you cannot. The compiler does not know
A
(which resolves toObject
) 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:
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.
but it's probably not what you want to do.
After reading your comments it sounds like what you really want to do is:
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.
In fact, you can invoke a static method on a type parameter (although it isn't done dynamically).
Try this:
I have no idea why the language designers decided it was a good idea to allow this.
This is not possible because the
A
type will not necessarily contain anadd()
method. The compiler will not permit this, because it can't guarantee that it will work.