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?

5
  • @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. Commented Jan 29, 2011 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<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. Commented Jan 29, 2011 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. Commented Jan 29, 2011 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. Commented Jan 29, 2011 at 14:55
  • Why what? Maybe stackoverflow.com/questions/3251269/… could help? Commented Jan 29, 2011 at 15:05

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

And put it in the abstract class which your classes need to extend.
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> ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.