Java 泛型 - 类<接口(interface)>

标签 java generics

我创建了一个名为标识符的接口(interface)。实现 Identifier 接口(interface)的类是 MasterEntity bean,如下所示。

public class MasterEntity implements Identifier{

}

在 DAO 方法中,我编写了如下方法签名的方法。

public Identifier getEntity(Class<Identifier> classInstance){

}

现在我想从服务中调用如下方法。

dao.getEntity(MasterEntity.class);

但是我收到编译错误说 -

The method getEntity(Class<Identifiable>) in the type ServiceAccessObject 
is not applicable for the arguments (Class<MasterEntity>)

我知道如果我像下面这样使用它就会起作用。

public Identifier getEntity(Class classInstance){

但是通过指定类型为可识别的Class,如何才能做到呢?

最佳答案

将 DAO 方法签名更改为

public Identifier getEntity(Class<? extends Identifier> classInstance)

通过如上所述声明方法,您指定唯一适用的参数是 Identifier.class本身。能够接受Identifier.class实现,你应该定义 generic type bounds .

List<? extends Shape> is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

您也可以看看这个答案:https://stackoverflow.com/a/897973/1782379

关于Java 泛型 - 类<接口(interface)>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41608736/

相关文章:

java - eclipse 自动且可追溯地将对象添加到类中

java - 如何取出字符串中的每个字符,并按倒序排列?

java - 使用对泛型对象的非类型化引用时,遍历成员类型化集合失败

java - 在发送到 Rest Web 服务之前解析和编码 URL

java - 从 DefaultTableModel 中删除后使用该行的数据

java - 使用 gradle 生成一个链接 LibGDX 项目 Assets 的 JAR 文件

c# - 无法将派生类型隐式转换为其基本泛型类型

Java Generic - 如何组合静态函数?

string - 在 Rust 中,将 &str 拆分为每个包含一个字符的 &strs 迭代器的惯用方法是什么?

c# - 如何列出实现抽象类和接口(interface)(C#)的东西?