2

I'm using generics like this: public class MyList<T>. Is there any way to ensure that the class represented by T implements a certain static method?

ryyst
  • 9,563
  • 18
  • 70
  • 97
  • @Kirk Woll: I'm trying to avoid having to subclass stuff or having to declare methods non-static that really should be static. At the same time, I want to keep my code as concise as possible using generics. – ryyst Jan 29 '11 at 14:46
  • @user, my point is that even if you *could* add such a constraint, it would be pointless as there is nothing you could do with that ability from within your generic `MyList` in the first place. You would not be able to invoke those static methods from within your generic list -- you cannot do anything with static members via generic parameters. – Kirk Woll Jan 29 '11 at 14:50
  • IMHO, your method should not be static. Even if you need a method returning the same value for each instance and not using `this` at all, it shouldn't be static (which took me once long to comprehend). There are in fact just few uses for static methods. – maaartinus Jan 29 '11 at 14:54
  • @Kirk Woll: Basically, I got some very similar classes. Part of these classes is checking whether a given string matches with the required format. I do that checking with a static method. I'm currently implementing the classes using generics. So I have to somehow check the format. I obviously could make the format-checking method non-static but I'm looking for a more elegant solution. – ryyst Jan 29 '11 at 14:55
  • Why what? Maybe http://stackoverflow.com/questions/3251269/when-to-use-static-classes-and-methods could help? – maaartinus Jan 29 '11 at 15:05

2 Answers2

2

No, even without generics there is never a way to ensure a class implements a static method.

You can, however, create a generic static method.

public static <T> List<T> makeSingletonList(T item) {
      ArrayList<T> result = new ArrayList<T>();
      result.add(item);
      return result;
}
Pace
  • 41,875
  • 13
  • 113
  • 156
2

Unfortunately not.

As an alternative, consider whether the static methods of your class belongs in some sort of associated class like a builder:

class Person {
    public static Person createFromDatastore(Datastore datastore) { ... }
}

It may be better to move the static to a separate class as a non-static method:

class PersonBuilder implements Builder<Person> {
     public Person createFromDatastore(Datastore datastore) { ... }
}

This means that you can dictate clients of your generic class can now be required to provide it:

public class MyList<B extends Builder<T>, T> ...
Jeremy
  • 22,188
  • 4
  • 68
  • 81
Bert F
  • 85,407
  • 12
  • 106
  • 123