[英]Java generics compile error “Class<capture#1-of ? …”
我在個人Java項目中使用javax.swing.event.EventListenerList
類很麻煩。 這不是一個簡單的例子,所以我舉了一個有相同問題的簡單例子。
package test;
public class GenericTest {
public static void main(String[] args) {
GenericTest gt = new GenericTest();
gt.doTest(String.class);
}
private void doTest(Class<? extends Comparable> type) {
doSomething(type, "test"); // Compile error :
// The method doSomething(Class<C>, C)
// in the type GenericTest is not applicable for the arguments
// (Class<capture#1-of ? extends Comparable>, String)
}
// third party API like javax.swing.event.EventListenerList.add()
private <C extends Comparable> void doSomething(Class<C> ct, C c) {
// ...
}
}
我在代碼中遇到了泛型編譯錯誤。
我有很多類都擴展了java.lang.Comparable
類的特定接口,我想用代碼中的doTest()
類的單個方法來處理所有這些類。
有人可以幫助我嗎?
在doSomething
中將c
定義為Comparable
或String
:
doTest(String.class);
}
private static void doTest(Class<? extends Comparable> type) {
doSomething(type, "test");
}
// third party API like javax.swing.event.EventListenerList.add()
private static <C extends Comparable> void doSomething(Class<C> ct, Comparable c) {
// ...
}
請注意,您不能從Object
, String
或Comparable
to C
隱式轉換。 要獲得更多見解,請在doSomething
內部嘗試執行以下操作:
C s = c; //Type mismatch: cannot convert from Comparable to C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.