考慮下面的類指定與參數
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
}
}
這有效泛型目前用作:
public SomeQueryUnsafe createCommentQueryUnsafe() {
return new SomeQueryUnsafe();
}
public void test() {
createCommentQueryUnsafe().setSort(CommentSortBy.CREATION, new Date());
}
雖然這工作,問題是createCommentQueryUnsafe()
不會對sortBy
指定限制。用戶可以自由地通過UserSortBy.NAME
即使這在這方面並沒有什麼意義
因爲剛加入<B extends SortBy>
到類簽名意味着我失去限制min
參數的能力,我無法弄清楚如何做到寫這雖然在該方法中。我不能使用像<M, S extends B & SortBy<M>>
那樣的its a compiler error。其他使用通配符的嘗試只會導致更多的複雜性和編譯錯誤。移動分揀到createCommentQuery()
方法將意味着每一個查詢需要2種方法,這是重複的代碼一個瘋狂的金額
我怎麼可能寫的仿製藥,從而createCommentQuery()
限制sortBy
參數只是CommentSortBy
同時還具有min
限於SortBy類中的S參數?
首先,有許多 「創造」 的方法:'createUserQuery()','createCommentQuery()',等等。每個都需要創建一個查詢,以將sortBy值限制爲其特定的上下文。你所做的只是讓create方法返回通用版本,它仍然讓'createCommentQuery()'接受'UserSortBy.NAME',這是一個完全無效的註釋值。 – TheLQ
理想情況下'createCommentQuery()'會返回類似'SomeQuery'這意味着sortBy只接受'sortBy(CommentSortBy.CREATION,someDate)'和'sortBy(CommentSortBy.VOTES,5L)',但不會'sortBy (UserSortBy.NAME,「Sam」)' –
TheLQ
@TheLQ這是有道理的,但不會調用'SomeQueryUnsafe。,Object> create()'來接近施加該限制嗎? (暫時忽略不靈活的'M'參數)。 –