gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:01:33 26 4
gpt4 key购买 nike

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

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

为什么?

编辑

哦哦不!我的 sample 错了! ... grrrrrr ... 对不起!

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);
}
}

如果你需要确定 T 是一个 GenericsTest,那么使用:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com