[英]How to use type parameter within method declaration instead of class
我有這段代碼可以工作:
接口:
public interface Queries<T> {
List<User> runQuery(T query);
}
並使用界面:
public class UserQueries implements Queries<UserQuery> {
@Override
List<User> runQuery(UserQuery q){
}
}
我想用以下代碼替換上面的內容,但是,它不起作用:
新介面:
public interface Queries {
// I want to pass the type parameter within the abstract method instead of the using Queries<T>
<T> List<User> runQuery(T query);
}
並使用新的界面(版本2):
public class UserQueries implements Queries {
// does not work, compiler complains:
// "The method runQuery(UserQuery) of type UserQueries must override or implement a supertype method
@Override
List<User> runQuery(UserQuery q) {
}
}
如何在類的方法intead中使用類型參數<T>
?
您正在嘗試混合兩個概念,一個是泛型,另一個是繼承。
版本1在版本1中,您具有通用接口
public interface Queries<T>
在實現中,您將其限制為接受UserQuery
類型
public class UserQueries implements Queries<UserQuery> {
版本2在版本2中,您具有使用通用抽象方法的具體接口
public interface Queries {
// I want to pass the type parameter within the abstract method instead of the using Queries<T>
<T> List<User> runQuery(T query);
}
因此,如果實現Queries
接口,則必須提供所有抽象方法的實現(如果更改方法簽名或方法的語法,則該方法在類中被視為不同的方法,而在接口中則被視為抽象方法)
這是由於Java的Type Erasures而發生的 。 此處發生的是,編譯后,此代碼<T> List<User> runQuery(T query)
更改為List<User> runQuery(Object query)
。 這就是為什么在子類中不能使用具體實現的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.