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?
2 Answers
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; } 1 Comment
BalusC
And put it in the abstract class which your classes need to extend.
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> ...
MyList<T>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.thisat all, it shouldn't be static (which took me once long to comprehend). There are in fact just few uses for static methods.