In Java, I'd like to have something as:
class Clazz<T> {
static void doIt(T object) {
// shake that booty
}
}
But I get
Cannot make a static reference to the non-static type T
I don't understand generics beyond the basic uses and thus can't make much sense of that. It doesn't help that I wasn't able to find much info on the internet about the subject.
Could someone clarify if such use is possible, by a similar manner? Also, why was my original attempt unsuccessful?
@BD at Rivenhill: Since this old question has gotten renewed attention last year, let us go on a bit, just for the sake of discussion. The body of your
doIt
method does not do anythingT
-specific at all. Here it is:So you can entirely drop all type variables and just code
Ok. But let's get back closer to the original problem. The first type variable on the class declaration is redundant. Only the second one on the method is needed. Here we go again, but it is not the final answer, yet:
However, it's all too much fuss about nothing, since the following version works just the same way. All it needs is the interface type on the method parameter. No type variables in sight anywhere. Was that really the original problem?
Something like the following would get you closer
EDIT: Updated example with more detail
I ran into this same problem. I found my answer by downloading the source code for
Collections.sort
in the java framework. The answer I used was to put the<T>
generic in the method, not in the class definition.So this worked:
Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:
Since static variables are shared by all instances of the class. For example if you are having following code
T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables
Others have answered your question already, but in addition I can thoroughly recomment the O'Reilly Java Generics book. It's a subtle and complex subject at times, and if often seems to have pointless restrictions, but the book does a pretty good job of explaining why java generics are the way they are.
Java doesn't know what
T
is until you instantiate a type.Maybe you can execute static methods by calling
Clazz<T>.doit(something)
but it sounds like you can't.The other way to handle things is to put the type parameter in the method itself:
which doesn't get you the right restriction on U, but it's better than nothing....