java - 一般错误 : type . .. 不适用于参数

标签 java generics

好的。假设我有以下小界面:

public interface MyInterface {
  void interfaceMethod();
}

以及一个实现此接口(interface)的类:

public class GenericsTest implements MyInterface {
  @Override
  public void interfaceMethod() {
    // do something
  }
}

这很简单!

现在我还有另一个使用泛型类型的类 <T extends MyInterface> :

public class AnotherClass<T extends MyInterface> {
  public void doSomethingWith(T obj) {
    System.out.println(obj.toString());
  }
}

现在我不明白这一点。如果我想调用 AnotherClass.doSomethingWith(T) 方法,如下面的代码片段所示(这个类是错误的;请参阅下面我的编辑):

public class ClassWithError {
  public ClassWithError(AnotherClass<? extends MyInterface> another) {
    another.doSomethingWith(another);
  }
}

我收到以下错误:

The method doSomethingWith(capture#1-of ? extends MyInterface) in the type 
AnotherClass<capture#1-of ? extends MyInterface> is not applicable for the 
arguments (AnotherClass<capture#2-of ? extends MyInterface>)

为什么会这样?

编辑

噢噢不!我的样本是错误的! ... grrrrrrr ... 抱歉!!

ClassWithError 必须正确:

public class ClassWithError {
  public ClassWithError(AnotherClass<? extends MyInterface> another, GenericsTest test) {
    another.doSomethingWith(test);
  }
}

然后错误是:

The method doSomethingWith(capture#1-of ? extends MyInterface) in the type 
AnotherClass<capture#1-of ? extends MyInterface> is not applicable for the 
arguments (GenericsTest)

最佳答案

AnotherClass#doSomethingWith 正在等待 T 类型的参数,即 MyInterface 的子类型。在 ClassWithError 中,您传递的是 AnotherClass 的实例,它不履行此约定。

doSomethingWith 签名更改为(示例):

public void doSomethingWith(AnotherClass<?> obj)

或者将 ClassWithError 的正文更改为(示例):

public ClassWithError(AnotherClass<GenericsTest> another) {
    GenericsTest instance = /* ... */;
    another.doSomethingWith(instance);
}

编辑

使用新的代码片段,参数化构造函数可能是一个通用的解决方案:

public class ClassWithError {
    public <T extends MyInterface> ClassWithError(AnotherClass<T> another, T test) {
        another.doSomethingWith(test);
    }
}

如果您需要确保 TGenericsTest,则使用:

public class ClassWithError {
    public <T extends GenericsTest> ClassWithError(AnotherClass<T> another, T test) {
        another.doSomethingWith(test);
    }
}

或者简单地说:

public class ClassWithError {
    public ClassWithError(AnotherClass<GenericsTest> another, GenericsTest test) {
        another.doSomethingWith(test);
    }
}

关于java - 一般错误 : type . .. 不适用于参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26360518/

相关文章:

c# - 继承和共享静态字段

java - 如何在 Spring Boot 应用程序中使用 JPA 删除/获取列表

java - 表格未显示图像

java - WSO2:点对点消息传递

c# - 实现通用接口(interface)时奇怪的 C# 行为

c# - 生成引用自身的类

java - 容器 'Maven Dependencies' 引用了不存在的库 - STS

java - Listview cacheColorHint 有问题吗?

generics - 如何将 Typescript 函数的泛型参数类型限制为枚举

Java 泛型返回类型