java - 如何在方法声明中使用类型参数而不是类
问题描述
我有这个工作的代码:
界面:
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) {
}
}
如何<T>
在类的方法中使用类型参数?
解决方案
您正在尝试混合 2 个概念,一个是泛型,另一个是继承。
版本 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
接口,则必须提供所有抽象方法的实现(如果您更改方法的方法签名或语法,则该方法被视为类中的不同方法,而不是接口中的抽象方法)
推荐阅读
- c++ - 创建一个进程,指定要在其上运行的 NUMA 节点
- pandas - 循环数据框并填充值
- postgresql - Postgres string_agg 函数未被识别为聚合函数
- objective-c - 使用 Objective Sharpie 创建 IOS Binding 项目时缺少 CFNetwork 参考
- c++ - asin 使用 Clang 在不同平台上产生不同的答案
- api - 有什么方法可以通过 API 调用访问私有数据集
- python - Flask - 从守护进程收到的截断或过大的响应标头
- ubuntu - Flask / Python3.7 jinja2.exceptions.UndefinedError: 'list object' has no attribute 'page'
- filenet-p8 - FileNet:获取存储区域上的可用空间
- excel - 从一个工作簿中选择用户窗体上的组合框会导致激活工作表出现问题