如何在方法声明而不是类中使用类型参数

时间:2019-05-18 17:13:07

标签: java generics

我有这个有效的代码:

接口:

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 个答案:

答案 0 :(得分: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接口,则必须提供所有抽象方法的实现(如果更改方法签名或方法的语法,则该方法在类中被视为不同的方法,但在类中则被视为抽象方法。界面)

答案 1 :(得分:0)

这是由于 Java的类型擦除而发生的。 这里发生的是,编译后,此代码<T> List<User> runQuery(T query)更改为List<User> runQuery(Object query)。这就是为什么在子类中不能使用具体实现的原因。

For you reference: Type Erasures in Java

相关问题