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?
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;
}
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> ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.