2013-09-21 50 views
2

鑑於這種原型:如果類<Type>使用類型,我該如何獲得通用類型?類型擴展?

public static <C extends SetComposite, S extends Iterable<U>, U> boolean 
eligibleForInclusion(C me, Class<C> clazz, List<S> members) throws TypeCollisionException { 
    ... 
} 

而且該調用位置:

public void include(RestaurantSet member) { 
    if (SetCompositeUtils.<RestaurantSetComposite, RestaurantSet, Restaurant> 
      eligibleForInclusion(this, this.getClass(), Arrays.asList(member))) { 
     inc.add(member); 
    } 
} 

的Eclipse編譯器會發出此錯誤:如果我讀正確

The parameterized method <RestaurantSetComposite, RestaurantSet, Restaurant>eligibleForInclusion(RestaurantSetComposite, Class<RestaurantSetComposite>, List<RestaurantSet>) of type SetCompositeUtils is not applicable for the arguments (RestaurantSetComposite, Class<capture#1-of ? extends RestaurantSetComposite>, List<RestaurantSet>) 

Class<capture#1-of ? extends RestaurantSetComposite>不匹配Class<RestaurantSetComposite> 。我能以某種方式解決這個問題嗎?

+0

你爲什麼要明確指定類型的參數,當你打電話?如果你已經明確指定了'C',那麼對'Class '類型的參數做'this.getClass()'有什麼意義? – newacct

+0

我指定類型參數來強制使用正確的靜態方法(我認爲不指定這些會導致難以發現編程錯誤)。第二部分,提供類,是因爲我基於類的桶,並且類型擦除使得它不可能(如java 1.7)來確定我在運行時處理的C的哪個子類。 –

+0

我想說的是,你明確指定它的方式不是'RestaurantSetComposite.class'唯一可能有效的第二個參數嗎?爲什麼不直接使用? – newacct

回答

2

因爲你this可能是一個的實例,this.getClass()可能不完全RestaurantSetComposite.class,所以你需要

public static <C extends SetComposite, S extends Iterable<U>, U> boolean 
eligibleForInclusion(C me, Class<? extends C> clazz, List<S> members) throws TypeCollisionException { 
    ... 
} 
+0

這絕對是更接近,但仍然不會編譯:「推斷類型Test.RestaurantSet不是一個有效的替代有界參數''S擴展Iterable >'」 –

+1

@MattBall我無法重現。但是什麼是'RestaurantSet'?如果'RestaurantSet'實現'Iterable ' - 也許通過'Set ' - 那麼沒有編譯錯誤。如果它實現了'Iterable <?擴展了Restaurant>'或'Iterable ',那麼確實存在你引用的編譯錯誤。那麼你也需要'S擴展Iterable '。 – Jeremy

+0

RestaurantSet確實實現了Iterable 。 –