How to define generic super type for static factory method?
Posted
by Esko
on Stack Overflow
See other posts from Stack Overflow
or by Esko
Published on 2010-06-14T10:04:53Z
Indexed on
2010/06/14
10:22 UTC
Read the original article
Hit count: 305
If this has already been asked, please link and close this one.
I'm currently prototyping a design for a simplified API of a certain another API that's a lot more complex (and potentially dangerous) to use.
Considering the related somewhat complex object creation I decided to use static factory methods to simplify the API and I currently have the following which works as expected:
public class Glue<T> {
private List<Type<T>> types;
private Glue() { types = new ArrayList<Type<T>>(); }
private static class Type<T> {
private T value;
/* some other properties, omitted for simplicity */
public Type(T value) { this.value = value; }
}
public static <T> Glue<T> glueFactory(String name, T first, T second) {
Glue<T> g = new Glue<T>();
Type<T> firstType = new Glue.Type<T>(first);
Type<T> secondType = new Glue.Type<T>(second);
g.types.add(firstType);
g.types.add(secondType);
/* omitted complex stuff */
return g;
}
}
As said, this works as intended. When the API user (=another developer) types Glue<Horse> strongGlue = Glue.glueFactory("2HP", new Horse(), new Horse());
he gets exactly what he wanted.
What I'm missing is that how do I enforce that Horse
- or whatever is put into the factory method - always implements both Serializable
and Comparable
? Simply adding them to factory method's signature using <T extends Comparable<T> & Serializable>
doesn't necessarily enforce this rule in all cases, only when this simplified API is used. That's why I'd like to add them to the class' definition and then modify the factory method accordingly.
PS: No horses (and definitely no ponies!) were harmed in writing of this question.
© Stack Overflow or respective owner