首页 > 解决方案 > 如何在方法声明中使用类型参数而不是类

问题描述

我有这个工作的代码:

界面:

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>在类的方法中使用类型参数?

标签: javagenerics

解决方案


您正在尝试混合 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接口,则必须提供所有抽象方法的实现(如果您更改方法的方法签名或语法,则该方法被视为类中的不同方法,而不是接口中的抽象方法)


推荐阅读