consider 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 used as:
public somequeryunsafe createcommentqueryunsafe() { return new somequeryunsafe(); } public void test() { createcommentqueryunsafe().setsort(commentsortby.creation, new date()); }
while works, problem createcommentqueryunsafe()
not specify limits on sortby
. users free pass usersortby.name
though make no sense in context
i can't figure out how write though because adding <b extends sortby>
class signature means loose ability restrict min
parameter in method. can't use <m, s extends b & sortby<m>>
its compiler error. other attempts wildcard magic result in more complexity , compiler errors. moving sorting createcommentquery()
method mean every single query needs 2 methods, crazy amount of duplicated code
how can possibly write generics createcommentquery()
limits sortby
parameter commentsortby
while still having min
restricted s parameter in sortby class?
this indeed tricky issue reasons you've pointed out. tried various approaches defeated generics limitation cited. seems you'll need make design changes if want specified type safety.
using inheritance hierarchy of sortby
implementations generic type restrictions seems have led impasse in particular. tried decoupling restriction new type parameter on sortby
, stands queried object itself, e.g. comment
, user
, etc. design came with:
static class comment { } static class user { } interface sortby<t, m> { } static class commentsortby<m> implements sortby<comment, m> { static final commentsortby<date> creation = new commentsortby<date>(); static final commentsortby<integer> votes = new commentsortby<integer>(); } static class usersortby<m> implements sortby<user, m> { static final usersortby<string> name = new usersortby<string>(); } static class query<t> { public <m> void setsort(sortby<t, m> sortby, m min) { //set relevant values } } public static void main(string[] args) { new query<comment>().setsort(commentsortby.creation, new date()); new query<comment>().setsort(usersortby.name, "joe"); //compiler error }
(ideone)
Comments
Post a Comment