[英]How to use type parameter within method declaration instead of class
I have this code which work: 我有这段代码可以工作:
Interface: 接口:
public interface Queries<T> {
List<User> runQuery(T query);
}
and using the interface: 并使用界面:
public class UserQueries implements Queries<UserQuery> {
@Override
List<User> runQuery(UserQuery q){
}
}
I want to replace the above with the following code, however, it does not work: 我想用以下代码替换上面的内容,但是,它不起作用:
New Interface: 新介面:
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);
}
and using the new Interface (version 2): 并使用新的界面(版本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) {
}
}
How can I use type parameter <T>
within method intead of class? 如何在类的方法intead中使用类型参数<T>
?
You are trying to mix 2 concepts one is generics and another is inheritance. 您正在尝试混合两个概念,一个是泛型,另一个是继承。
Version 1 In version 1 you have generic interface 版本1在版本1中,您具有通用接口
public interface Queries<T>
And in the implementation you are restricting it to accept UserQuery
type 在实现中,您将其限制为接受UserQuery
类型
public class UserQueries implements Queries<UserQuery> {
Version 2 In version 2 you have concrete interface with generic abstract method 版本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);
}
So if you implement Queries
interface then you have to provide implementations of all abstract methods (if you change the method signature or syntax of method, that method is considered as different method in class but not the abstract method in interface) 因此,如果实现Queries
接口,则必须提供所有抽象方法的实现(如果更改方法签名或方法的语法,则该方法在类中被视为不同的方法,而在接口中则被视为抽象方法)
This is happening due to Java's Type Erasures . 这是由于Java的Type Erasures而发生的 。 What is happening here is that after compilation this code <T> List<User> runQuery(T query)
is changing to List<User> runQuery(Object query)
. 此处发生的是,编译后,此代码<T> List<User> runQuery(T query)
更改为List<User> runQuery(Object query)
。 So that's why in child class you can't use the concrete implementation. 这就是为什么在子类中不能使用具体实现的原因。
For you reference: Type Erasures in Java 供您参考:用Java键入Erasures
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.