Static method in a generic class?

André Chalella picture André Chalella · Jun 1, 2009 · Viewed 167.5k times · Source

In Java, I'd like to have something as:

class Clazz<T> {
  static void doIt(T object) {
    // ...
  }
}

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?

Answer

newacct picture newacct · Jun 1, 2009

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.