【问题标题】:Java Generics - Class<Interface>Java 泛型 - 类<接口>
【发布时间】:2017-01-12 08:53:05
【问题描述】:

我创建了一个名为 Identifier 的界面。实现 Identifier 接口的类是 MasterEntity bean,如下所示。

public class MasterEntity implements Identifier{

}

在DAO方法中,我写了一个类似下面方法签名的方法。

public Identifier getEntity(Class<Identifier> classInstance){

}

现在我想从 Service 调用如下方法。

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){

但是通过指定Identifiable类型的Class,如何做到呢?

【问题讨论】:

  • 试试Class&lt;? extends Identifiable&gt;
  • 我相信类型擦除是您第一次尝试失败的原因。但是您能向我们解释一下为什么您认为需要将类类型信息传递到您的方法中吗?
  • 你是对的。它的工作。非常感谢。

标签: java generics


【解决方案1】:

将 DAO 方法签名更改为

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

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

List&lt;? extends Shape&gt; 是有界通配符的示例。 ? 代表未知类型,就像我们之前看到的通配符一样。但是,在这种情况下,我们知道这种未知类型实际上是 Shape 的子类型。 (注意:它可以是 Shape 本身,也可以是某个子类;它不需要从字面上扩展 Shape。)我们说 Shape 是通配符的上限。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多