我對 Java 中的泛型編程有一個小問題。有沒有辦法檢查傳遞給方法的參數的類型?我想比較調用該方法的實例的類型以及傳遞給它的參數。如果它們不相同,則應停止該方法的操作(保護種類)。public void homeMatch(SportTeam<Type> visitors){ if(the type of visitors and this-object are not the same){ //do this } else{ //do something different }}
3 回答

守著一只汪
TA貢獻1872條經驗 獲得超4個贊
如果您真的想要進行檢查,您可以做的是將類參數添加到函數參數中。然后將 classParameter 與 this 的類進行比較。這會起作用,因為訪問者具有與 typeClass 相同的泛型類型。
public<Type> void homeMatch(Class<Type> typeClass, SportTeam<Type> visitors){
if (typeClass.getClass() == this.getClass()){
}
}
添加回答
舉報
0/150
提交
取消