Consider the following classes
public interface SortBy<S> {
}
public class CommentSortBy<S> implements SortBy<S> {
public static CommentSortBy<Date> CREATION = new CommentSortBy<Date>();
public static CommentSortBy<Integer> VOTES = new CommentSortBy<Integer>();
}
public class SomeQueryUnsafe {
public <M, S extends SortBy<M>> void setSort(S sortBy, M min) {
//Set relevant values
}
}
This is currently used as:
public SomeQueryUnsafe createCommentQueryUnsafe() {
return new SomeQueryUnsafe();
}
public void test() {
createCommentQueryUnsafe().setSort(CommentSortBy.CREATION, new Date());
}
While this works, the problem is that createCommentQueryUnsafe()
does not specify limits on sortBy
. Users are free to pass UserSortBy.NAME
even though that would make no sense in this context
I can't figure out how to do write this though because just adding <B extends SortBy>
to the class signature means I loose the ability to restrict the min
parameter in the method. I can't use something like <M, S extends B & SortBy<M>>
as its a compiler error. Other attempts with wildcard magic just result in significantly more complexity and compiler errors. Moving the sorting to the createCommentQuery()
method would mean every single query needs 2 methods, which is a crazy amount of duplicated code
How can I possibly write the generics so createCommentQuery()
limits the sortBy
parameter to just CommentSortBy
while still having min
restricted to the S parameter in the SortBy class?
`. I just loose compile time checking (and IDE autocompletion) of the `min` and `max` parameters. I'm really trying to avoid that though– TheLQ Jul 15 '13 at 17:27